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

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

问题描述

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

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天全站免登陆