gpt4 book ai didi

arrays - Nodejs : How would I find a specific key value pair in a JSON object

转载 作者:太空宇宙 更新时间:2023-11-04 03:05:35 24 4
gpt4 key购买 nike

Nodejs 中是否有一种方法可以在对象中的任何位置查找特定的键:值对,如果存在则返回 true。

即。是否在以下对象中的任何位置找到了“DeviceType”:“无效设备类型”

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

最佳答案

有大量方法包括遍历对象,但除非您正在做比示例更复杂的事情,否则我建议您将对象转换为字符串并使用.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);

关于arrays - Nodejs : How would I find a specific key value pair in a JSON object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41863155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com