有一噸的,其中包括通過對象迭代方法,但除非你正在做的事情複雜得多,你的榜樣,我會建議你將對象轉換爲字符串,並使用.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);
感謝這似乎是最直接的。我很感激。 – shaun