在深层嵌套对象中按特定键查找所有值 [英] Find all values by specific key in a deep nested object

查看:30
本文介绍了在深层嵌套对象中按特定键查找所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在深层嵌套对象中按特定键查找所有值?

How would I find all values by specific key in a deep nested object?

例如,如果我有一个这样的对象:

For example, if I have an object like this:

const myObj = {
  id: 1,
  children: [
    {
      id: 2,
      children: [
        {
          id: 3
        }
      ]
    },
    {
      id: 4,
      children: [
        {
          id: 5,
          children: [
            {
              id: 6,
              children: [
                {
                  id: 7,
                }
              ]
            }
          ]
        }
      ]
    },
  ]
}

我如何通过 id 的键获得这个 obj 的所有嵌套中的所有值的数组.

How would I get an array of all values throughout all nests of this obj by the key of id.

注意:children 是一个一致的名称,id 不会存在于 children 对象之外.

Note: children is a consistent name, and id's won't exist outside of a children object.

所以从 obj 中,我想生成一个这样的数组:

So from the obj, I would like to produce an array like this:

const idArray = [1, 2, 3, 4, 5, 6, 7]

推荐答案

你可以做一个这样的递归函数:

You could make a recursive function like this:

idArray = []

function func(obj) {
  idArray.push(obj.id)
  if (!obj.children) {
    return
  }

  obj.children.forEach(child => func(child))
}

您的示例的代码段:

const myObj = {
  id: 1,
  children: [{
      id: 2,
      children: [{
        id: 3
      }]
    },
    {
      id: 4,
      children: [{
        id: 5,
        children: [{
          id: 6,
          children: [{
            id: 7,
          }]
        }]
      }]
    },
  ]
}

idArray = []

function func(obj) {
  idArray.push(obj.id)
  if (!obj.children) {
    return
  }

  obj.children.forEach(child => func(child))
}

func(myObj)
console.log(idArray)

这篇关于在深层嵌套对象中按特定键查找所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆