【问题标题】:change object Structure based condition更改对象基于结构的条件
【发布时间】:2018-08-05 09:10:10
【问题描述】:

我有一个如下所示的对象,

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

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

}

我存档了祖父母和孩子,但卡在了子孩子中。

【问题讨论】:

  • I have a JSON - 不,你有一个 javascript 对象...... JSON 从来没有 var x = ... jSON 是一个对象的字符串表示......所以,你根本没有 JSON ...只是一个普通的 ol' javascript 对象 ...I am trying to reform the JSON structure based on parent and child relationship. - 请显示实际的预期输出,而不是一些只有你才能理解的晦涩表示

标签: javascript jquery arrays angularjs json


【解决方案1】:

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

【讨论】:

  • 注意克隆是浅拷贝。
猜你喜欢
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2015-05-29
  • 2018-01-08
  • 2016-10-09
  • 1970-01-01
相关资源
最近更新 更多