【问题标题】:Remove object from an array of hierarchical object [duplicate]从分层对象数组中删除对象[重复]
【发布时间】:2018-08-28 23:55:21
【问题描述】:

我有一个看起来像这样的数组:

var a = [
    {
      value: 'Some data',
      structure: 'linear',
      id: 0,
      children: [
        { id: 1, value: 'Some data', structure: undefined },
        { id: 2, 
          value: 'Some data',
          structure: 'linear', 
          children: [ 
           { id: 4, value: 'Some data', structure: undefined } 
          ] 
        }
      ]
    },
    {
      id: 5,
      structure: undefined
      value: 'Some data',
    },
   ];

我正在尝试删除结构值未定义的所有对象。 每个没有孩子的匹配对象,或孩子层次结构中的匹配,都不应该存在于输出数组中。 在运行时我不知道有多少级别的对象会有一个子数组

输出应该是这样的:

const output = [
 {
   value: 'Some data',
   structure: 'linear',
   id: 0,
   children: [
    { id: 2, value: 'Some data', structure: 'linear' }
   ]
 }
];

【问题讨论】:

  • 寻找深度克隆,然后添加过滤。
  • @DenysSéguret,这两个问题略有不同。

标签: javascript


【解决方案1】:

递归地映射数据,然后过滤未定义的值后返回结果,如

var a = [
  {
    value: 'Some data',
    structure: 'linear',
    id: 0,
    children: [
      { id: 1, value: 'Some data', structure: undefined },
      {
        id: 2,
        value: 'Some data',
        structure: 'linear',
        children: [
          { id: 4, value: 'Some data', structure: undefined }
        ]
      }
    ]
  },
  {
    id: 5,
    structure: undefined,
    value: 'Some data',
  },
];
const getReducedArr = (data) => {
  return data.map((obj) => {
    if (obj.structure) {
      const children = obj.children ? getReducedArr(obj.children) : [];
      return {
        ...obj,
        ...(children.length > 0 ? { children } : undefined)
      }
    }
  }).filter(data => data !== undefined)
}

const res = getReducedArr(a);


console.log(res)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2016-03-12
    • 2021-07-01
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多