Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从层次对象数组中删除对象_Javascript - Fatal编程技术网

Javascript 从层次对象数组中删除对象

Javascript 从层次对象数组中删除对象,javascript,Javascript,我有一个数组,看起来像这样: var a = [ { value: 'Some data', structure: 'linear', id: 0, children: [ { id: 1, value: 'Some data', structure: undefined }, { id: 2, value: 'Some data', structure: 'line

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

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' }
   ]
 }
];
我试图删除所有结构值未定义的对象。 输出数组中不应存在没有子对象的每个匹配对象或子层次结构中的匹配对象。 我不知道在运行时有多少级别的对象将具有子数组

输出应如下所示:

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' }
   ]
 }
];

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

var a=[
{
值:“某些数据”,
结构:'线性',
id:0,
儿童:[
{id:1,值:'Some data',结构:undefined},
{
id:2,
值:“某些数据”,
结构:'线性',
儿童:[
{id:4,值:'Some data',结构:undefined}
]
}
]
},
{
id:5,
结构:未定义,
值:“某些数据”,
},
];
常量getReducedArr=(数据)=>{
返回数据.map((obj)=>{
if(对象结构){
const children=obj.children?getreducedar(obj.children):[];
返回{
…obj,
…(children.length>0?{children}:未定义)
}
}
}).filter(数据=>数据!==未定义)
}
常数res=getreducedar(a);

console.log(res)
寻找深度克隆,只需添加过滤即可。@DenysSéguret,这两个问题之间略有不同。