如何在嵌套对象数组中找到特定键的所有值?
示例数据:
[
{
"id": 14252373,
"name": "foo",
"url": "/test",
"private": true,
"owner": {
"login": "username",
"id": 1217786,
},
"permissions": {
"admin": {
"id": 1567283
},
"push": false,
"pull": true
}
}
]
我将如何获得所有id
值的数组?
期望的输出: [14252373, 1217786, 1567283]
您可以创建一个函数并遍历传递对象中的键。如果当前键与要查找的键相同,则将该值添加到输出中。如果当前键是一个对象,则递归调用当前值上的函数
function getValue(o, findKey) {
const output = []
for (const k in o) {
if (k === findKey)
output.push(o[k])
else if (typeof o[k] === 'object')
output.push(...getValue(o[k], findKey))
}
return output;
}
getValue(input, 'id')
这是一个片段:
const input = [{
"id": 14252373,
"name": "foo",
"url": "/test",
"private": true,
"owner": {
"login": "username",
"id": 1217786,
},
"permissions": {
"admin": {
"id": 1567283
},
"push": false,
"pull": true
}
}]
function getValue(o, findKey) {
const output = []
for (const k in o) {
if (k === findKey)
output.push(o[findKey])
else if (typeof o[k] === 'object')
output.push(...getValue(o[k], findKey))
}
return output;
}
console.log(getValue(input, 'id'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句