让我们从一个简单的例子开始,以更好地理解我的问题,我有这个对象:
{
"list_of_objects" : [
{
"name" : "0",
"interesting_key" : "some_value",
},
{
"name" : "1",
"interesting_key" : "some_other_value",
"list_of_objects" : [
{
"name" : "10",
"interesting_key" : "something"
},
{
"name" : "11"
},
]
},
{
"name" : "2",
"interesting_key" : "again_some_other_value",
}
]
}
我想获取与interesting_key
相对应的所有值,有没有一种方法可以在不循环访问每个对象列表的情况下?这样的结果:
["some_value", "some_other_value", "something", "again_some_other_value"]
我想这样做,所以我只能比较包含interesting_key
的对象。
在此先感谢您的帮助,
答案 0 :(得分:2)
您可以像这样递归搜索密钥:
const list_of_objects=[{"name":"0","interesting_key":"some_value",},{"name":"1","interesting_key":"some_other_value","list_of_objects":[{"name":"10","interesting_key":"something"},{"name":"11"},]},{"name":"2","interesting_key":"again_some_other_value",}]
function findNestedValues(array, key) {
return array.reduce((r, obj) => {
if(key in obj)
r.push(obj[key])
if(obj.list_of_objects)
r.push(...findNestedValues(obj.list_of_objects, key))
return r
}, [])
}
console.log(findNestedValues(list_of_objects, "interesting_key"))
答案 1 :(得分:1)
这是一个字符串版本
const re = /"interesting_key":"(.*?)"/g
const str=JSON.stringify({"list_of_objects":[{"name":"0","interesting_key":"some_value",},{"name":"1","interesting_key":"some_other_value","list_of_objects":[{"name":"10","interesting_key":"something"},{"name":"11"},]},{"name":"2","interesting_key":"again_some_other_value",}]});
let result = [];
while ((match = re.exec(str)) != null) {
result.push(match[1])
}
console.log(result)
更短
const re = /"interesting_key":"(.*?)"/g
const str=JSON.stringify({"list_of_objects":[{"name":"0","interesting_key":"some_value",},{"name":"1","interesting_key":"some_other_value","list_of_objects":[{"name":"10","interesting_key":"something"},{"name":"11"},]},{"name":"2","interesting_key":"again_some_other_value",}]});
let result = []
str.replace(re,(a,b) => result.push(b) )
console.log(result)
答案 2 :(得分:0)
您可以创建一个递归函数,该函数遍历数据,如以下代码所示:
var list = [
{
"name" : "0",
"interesting_key" : "some_value",
},
{
"name" : "1",
"interesting_key" : "some_other_value",
"list_of_objects" : [
{
"name" : "10",
"interesting_key" : "something"
},
{
"name" : "11"
},
]
},
{
"name" : "2",
"interesting_key" : "again_some_other_value",
}
]
var interestingKey = [];
function getInterestingKey (list) {
list.forEach(function(item) {
if (item.interesting_key) {
interestingKey.push(item.interesting_key);
}
if (item.list_of_objects) {
getInterestingKey(item.list_of_objects);
}
})
return interestingKey;
}
console.log(getInterestingKey(list))