2017-01-25 146 views
0

Nodejs中是否有一種方法可以在對象中的任意位置找到特定鍵:值對,如果存在,則返回true。Nodejs:如何在JSON對象中找到特定的鍵值對

即, "DeviceType" : "Invalid Device Type"在以下對象的任何地方找到?

{ 
    "Config": { 
     "Device": [{ 
      "DeviceType": 1, 
      "Firmware": 216 
     }], 
     "Mobile": [{ 
      "DeviceType": "Invalid Device Type" 
     }, { 
      "DeviceType": "Invalid Device Type" 
     }] 
    } 
} 

回答

1

您可以這樣做:

var j = { 
    "Config": { 
     "Device": [{ 
      "DeviceType": 1, 
      "Firmware": 216 
     }], 
     "Mobile": [{ 
      "DeviceType": "Invalid Device Type" 
     }, { 
      "DeviceType": "Invalid Device Type" 
     }] 
    }  
}; 
var v = JSON.stringify(j); 
var n = v.search('"DeviceType":"Invalid Device Type"'); // no white spaces between key value 
if (n >= 0) 
    console.log('found it!'); 
+0

感謝這似乎是最直接的。我很感激。 – shaun

3

有一噸的,其中包括通過對象迭代方法,但除非你正在做的事情複雜得多,你的榜樣,我會建議你將對象轉換爲字符串,並使用.indexOf方法來確定字符串被包含在對象字符串中:

var obj = { 
    "Config": { 
     "Device": [{ 
      "DeviceType": 1, 
      "Firmware": 216 
     }], 
     "Mobile": [{ 
      "DeviceType": "Invalid Device Type" 
     }, { 
      "DeviceType": "Invalid Device Type" 
     }] 
    } 
}; 

var objString = JSON.stringify(obj); 
var childString = "\"DeviceType\":\"Invalid Device Type\""; 
var isStringPresent = objString.indexOf(childString) >= 0; 
console.log(isStringPresent); // true 

childString = "\"DeviceType\":\"asdfasfd\""; 
isStringPresent = objString.indexOf(childString) >= 0; 
console.log(isStringPresent); // false 

也可以封裝成邏輯的方法:

function isStringContainedInObject(obj, str) { 
    var objString = JSON.stringify(obj); 
    return objString.indexOf(str) >= 0; 
} 

// invoke it 
var obj = { 
    "Config": { 
     "Device": [{ 
      "DeviceType": 1, 
      "Firmware": 216 
     }], 
     "Mobile": [{ 
      "DeviceType": "Invalid Device Type" 
     }, { 
      "DeviceType": "Invalid Device Type" 
     }] 
    } 
}; 
var str = "\"DeviceType\":\"Invalid Device Type\""; 
isStringContainedInObject(obj, str); 
相關問題