【问题标题】:How to get all specific values from an array of objects with nested arrays of objects?如何从具有嵌套对象数组的对象数组中获取所有特定值?
【发布时间】:2020-07-20 23:08:00
【问题描述】:

我有一个数组:

   const arr = [
  {
    name: "name 1",
    dontShow: true,
    children: [
      {
        name: "name 2",
        key4: 4,
        dontShow: false,
        children: [],
      },
    ],
  },
  {
    name: "name 3",
    dontShow: false,
    children: [
      {
        name: "name 4",
        dontShow: true,
        children: [
          {
            name: "name 5",
            dontShow: false,
            children: null,
          },
        ],
      },
    ],
  },
];

我需要每个对象的名称数组,除了具有属性dontShow: true 的对象 所以从那个例子中我会期待这样的数组:

["name2", "name3", "name5"]

基本上,我需要从树状结构中获取一个平面数组,lodash/下划线解决方案也很棒,我只是没有找到它们

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我尝试使用我的大脑但它完全没有希望,我想这里有一些递归函数会很棒
  • 请张贴您到目前为止尝试过的代码?

标签: javascript arrays object tree logic


【解决方案1】:

你可以使用递归函数

const arr = [{ name: "name 1", dontShow: true, children: [{  name:"name 2", key4: 4, dontShow: false, children: [], }, ],},{name: "name 3",dontShow: false,children: [{ name: "name 4", dontShow: true, children: [{ name: "name 5", dontShow: false, children: null,},],}, ],},];

let final = (arr, result = []) => {
  if (Array.isArray(arr)) {
    arr.forEach(obj => {
      if (!obj.dontShow) {
        result.push(obj.name)
      }
      if (Array.isArray(obj.children)) {
        final(obj.children, result)
      }
    })
  }
  return result
}

console.log(final(arr))

【讨论】:

    【解决方案2】:

    您可以通过查看dontShow 获得一组平面名称。

    const
        getNames = array => array.flatMap(({ name, dontShow, children }) => [
            ...(dontShow ? [] : [name]),
            ...getNames(children || [])
        ]),
        array = [{ name: "name 1", dontShow: true, children: [{ name: "name 2", key4: 4, dontShow: false, children: [] }] }, { name: "name 3", dontShow: false, children: [{ name: "name 4", dontShow: true, children: [{ name: "name 5", dontShow: false, children: null, }] }] }],
        result = getNames(array);
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多