【问题标题】:How to find all values of a specific key in an array of nested objects?如何在嵌套对象数组中查找特定键的所有值?
【发布时间】:2020-12-20 05:13:51
【问题描述】:
如何在嵌套对象数组中找到特定键的所有值?
示例数据:
[
{
"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]
【问题讨论】:
-
-
您是否可以灵活地使用某些第三方库?如果是,那么lodash 对于此类用例非常强大。
标签:
javascript
arrays
json
object
nested
【解决方案1】:
您可以创建一个函数并遍历传递对象中的键。如果当前键与要查找的键相同,则将该值添加到输出中。如果当前键是对象,则递归调用当前值上的函数
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')
这是一个sn-p:
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'))
【解决方案2】:
有多种方法可以做到这一点。一种有趣的方法是将结构转换为 JSON 并使用正则表达式提取 ID:
let ary =
[
{
"id": 14252373,
"name": "foo",
"url": "/test",
"private": true,
"owner": {
"login": "username",
"id": 1217786,
},
"permissions": {
"admin": {
"id": 1567283
},
"push": false,
"pull": true
}
}
];
let json = JSON.stringify(ary);
let idMatcher = /(?<="id":\s*)\d+/gmu;
let ids = json.match(idMatcher);
console.log(ids);
【解决方案3】:
您可以使用reduce 和recursive 函数。在reduce回调中检查当前迭代的项目是否为对象,如果是则调用递归函数
let data = [{
id: 14252373,
name: "foo",
url: "/test",
private: true,
owner: {
login: "username",
id: 1217786
},
permissions: {
admin: {
id: 1567283
},
push: false,
pull: true
}
}];
let ids = data.reduce((acc, curr) => {
for (let keys in curr) {
if (keys === "id") {
acc.push(curr[keys]);
} else if (typeof curr[keys] === "object" && curr[keys] !== null) {
acc = recurObj(curr[keys], acc);
}
}
return acc;
}, []);
function recurObj(val, arr) {
for (let keys in val) {
if (keys === "id") {
arr.push(val[keys]);
} else if (typeof val[keys] === "object" && val[keys] !== null) {
recurObj(val[keys], arr);
}
}
return arr;
}
console.log(ids);
【解决方案4】:
由于它是一个对象数组,我认为一个简单的 forEach 将有助于使这变得非常简单:
let data = [{
id: 14252373,
name: "foo",
url: "/test",
private: true,
owner: {
login: "username",
id: 1217786
},
permissions: {
admin: {
id: 1567283
},
push: false,
pull: true
},
},
{
id: 222222222,
name: "foo",
url: "/test",
private: true,
owner: {
login: "username",
id: 1217786
},
permissions: {
admin: {
id: 1567283
},
push: false,
pull: true
},
},
];
let everyID = [];
data.forEach(item => {
everyID.push(item.id);
});
console.log(everyID);
【解决方案5】:
我们将object-scan 用于许多数据处理任务。一旦您了解如何使用它,它就非常方便。以下是您如何回答您的问题
// const objectScan = require('object-scan');
const find = (input) => objectScan(['**.id'], { rtn: 'value' })(input);
const arr = [{ id: 14252373, name: 'foo', url: '/test', private: true, owner: { login: 'username', id: 1217786 }, permissions: { admin: { id: 1567283 }, push: false, pull: true } }];
console.log(find(arr));
// => [ 1567283, 1217786, 14252373 ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>
免责声明:我是object-scan的作者