简体   繁体   English

如何在嵌套对象数组中查找特定键的所有值?

[英]How to find all values of a specific key in an array of nested objects?

How would I find all values of a specific key in an array of nested objects?如何在嵌套对象数组中找到特定键的所有值?

Example data:示例数据:

[
  {
    "id": 14252373,
    "name": "foo",
    "url": "/test",
    "private": true,
    "owner": {
        "login": "username",
        "id": 1217786,
    },
    "permissions": {
        "admin": {
            "id": 1567283
        },
        "push": false,
        "pull": true
        }
  }
]

How would I get an array of all id values?我如何获得所有id值的数组?

Desired output: [14252373, 1217786, 1567283]所需 output: [14252373, 1217786, 1567283]

You could create a function and loop through the keys in the passed object. If the current key is same as the key to find, add the value to the output. If the current key is an object, recursively call the function on the current value您可以创建一个 function 并循环遍历传递的 object 中的键。如果当前键与要查找的键相同,则将该值添加到 output。如果当前键是 object,则递归调用 function 当前值

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')

Here's a snippet:这是一个片段:

 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'))

There are multiple ways to accomplish this.有多种方法可以实现这一点。 One interesting way is to convert the structure to JSON and extract the IDs using a regular expression:一种有趣的方法是将结构转换为 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);

You can use reduce and a recursive function. Inside the reduce callback check if the current item under iteration is an object or not, If so then call the recursive function您可以使用reducerecursive function。在 reduce 回调中检查迭代中的当前项目是否为 object,如果是则调用递归 function

 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);

Since it's an array of objects, I think a simple forEach would help make this really easy:由于它是一个对象数组,我认为一个简单的 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);

We use object-scan for many data processing tasks.我们将对象扫描用于许多数据处理任务。 Once you wrap your head around how to use it, it is quite handy.一旦您全神贯注于如何使用它,它就会非常方便。 Here is how you could answer your question这是你如何回答你的问题

 // 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>

Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Javascript 中的对象数组中找到特定键的所有唯一值? - How to find all unique values for specific key in array of objects in Javascript? 如何获取对象数组中特定键的所有值? - How to get all values of a specific key in array of objects? 如何在对象数组中查找特定键是否为真 - How to find if a specific key is true in Array of objects 如何从具有嵌套 arrays 对象的对象数组中获取所有特定值? - How to get all specific values from an array of objects with nested arrays of objects? 对象数组的嵌套数组迭代查找所有值搜索过滤器 - Nested Array Iteration for array of objects find all values search filter 如何根据嵌套对象数组的对象搜索输入查找所有匹配值 - how to find all matching values based on search input of objects for the nested array of objects 在深层嵌套 object 中按特定键查找所有值 - Find all values by specific key in a deep nested object 如何在不知道mongodb中的父键的情况下查找特定的嵌套对象 - How to find specific nested objects without knowing the parent key in mongodb 如果特定键的值相同,如何将值更新为嵌套的对象数组? - How to update the value into a nested array of objects if value for specific key is same? 如何更改嵌套对象数组 javascript 中的所有键名 - How to change all key name inside nested array of objects javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM