gpt4 book ai didi

javascript - 如何获取指定文本/字符而不是键值的 json 值

转载 作者:行者123 更新时间:2023-11-28 04:09:16 25 4
gpt4 key购买 nike

我有一个奇怪的要求,即按值从 JSON 对象中获取值,例如在下面的 json 对象中,如果我将值作为 Steve 传递而不是像这样的完整值,则其中有两个数组Steve Jon,如何循环整个 json 对象并在整个 json 对象中找到匹配的对象。我的 json 对象非常大,请建议我任何循环整个对象而不影响性能的好方法。我已经检查了 JSONPath 表达式,但它不起作用

提前致谢

grouped_people: {
'friends': [
{name: 'Steve Jon', country: 'NZ'},
{name: 'Jane Ken', country: 'US'},
{name: 'Mike Jhon', country: 'AU'},
{name: 'Mary Mani', country: 'NZ'},
],
'enemies': [
{name: 'Evil Steve', country: 'AU'},
{name: 'Betty', country: 'NZ'},
]
}

最佳答案

您可以使用递归函数来查找包含给定值的对象,如下所示。

var grouped_people = {
'friends': [{
name: 'Steve Jon',
country: 'NZ'
},
{
name: 'Jane Ken',
country: 'US'
},
{
name: 'Mike Jhon',
country: 'AU'
},
{
name: 'Mary Mani',
country: 'NZ'
},
],
'enemies': [{
name: 'Evil steve',
country: 'AU'
},
{
name: 'Betty',
country: 'NZ'
},
]
};

//Recursive function to search text in the object
function findObject(obj, text, callback) {
for (var k in obj) {
if (typeof obj[k] == "object" && obj[k] !== null) {
findObject(obj[k], text, callback);
} else {
if (obj[k].toLowerCase().indexOf(text.toLowerCase()) !== -1) {
callback(obj);
}
}
}
}


findObject(grouped_people, "Steve", function(obj) {
//All matched objects will return here.
console.log(obj);
});

关于javascript - 如何获取指定文本/字符而不是键值的 json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46439809/

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