改变对象基于结构的条件

时间:2018-02-25 23:25:12

标签: javascript jquery arrays angularjs json

我的对象如下所示,

我正在尝试根据父子关系改造对象结构。

var b = [];
for(var i=0;i<a.length;i++){
if(a[i].parent == null){
const children = a.filter(x => a[i].parent == null && a[i].id == x.parent);
b.push({'name':a[i].name,'type':'grandparent','children':children})
}

}

我将祖父母和孩子存档,但是他们被困在子女中。

1 个答案:

答案 0 :(得分:2)

您可以使用reduce()方法并为此创建递归函数。

var a = [{"id":0,"name":"Node 0","thumbnail":{"description":"Random Picture","href":""},"parent":null},{"id":1,"name":"Node 1","thumbnail":{"description":"Another Random Picture","href":""},"parent":0},{"id":2,"name":"Node 2","thumbnail":{"description":"A Picture Is Random","href":""},"parent":null},{"id":3,"name":"Node 3","thumbnail":{"description":"Picture, Random","href":""},"parent":1}]

function nested(arr, parentId) {
  return arr.reduce(function(r, e) {
    if (e.parent == parentId) {
      const children = nested(arr, e.id);
      const clone = Object.assign({}, e);
      if (children.length) clone.children = children
      r.push(clone)
    }
    return r;
  }, [])
}

const result = nested(a);
console.log(result)