2017-01-25 114 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); 
相关问题