javascript - 更改基于对象结构的条件

标签 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})
}

}

我归档了祖 parent 和 child ,但陷入了子 child 的困境。

最佳答案

您可以使用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)

关于javascript - 更改基于对象结构的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48979569/

相关文章:

javascript - jQuery 由于附加到 switch 语句的额外字符而失败

javascript - 如何 DRY http 成功和错误函数?

jquery - 如何防止模式弹出窗口在出现验证错误时提交表单

javascript - 如何使用 Moment.js 获取今天和每月最后一天之间的天数?

python - 使用 numpy 在多个维度上高效展开

javascript .push 通过复制新值来覆盖以前的数组值

javascript - 使用jquery从html中删除表格行

javascript - Angular : Code organisation of controllers

javascript - knockoutJS、requireJS 和 jQueryUI Datepicker 不能一起玩

javascript - 初始化一个 jquery 对话框