Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.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_Jquery_Arrays_Angularjs_Json - Fatal编程技术网

Javascript 基于条件更改对象结构

Javascript 基于条件更改对象结构,javascript,jquery,arrays,angularjs,json,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':childr

我有一个像下面这样的物体

我正试图改革基于父子关系的对象结构

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

}
var b=[];
对于(var i=0;ia[i]。parent==null&&a[i]。id==x.parent);
b、 push({'name':a[i].name,'type':'祖父母','children':children})
}
}
我归档了祖父母和孩子,但陷入了子孩子。

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

var a=[{“id”:0,“name”:“Node 0”,“缩略图”:{“description”:“Random Picture”,“href”:“}”,parent:null},{“id”:1,“name”:“Node 1”,“缩略图”:{“description”:“other Random Picture”,“href”:“}”,“name”:“Node 2”,“缩略图”:{“description”:“a Picture Is Random”,“href”:“},”parent:null},{“id”:3,“name”:“Node 3”,“缩略图”:{“description:“Picture,Random”,“href:”},“parent”:1}]
嵌套函数(arr,parentId){
返回arr.reduce(函数(r,e){
if(e.parent==parentId){
const children=嵌套(arr,e.id);
const clone=Object.assign({},e);
if(children.length)clone.children=children
r、 推送(克隆)
}
返回r;
}, [])
}
常量结果=嵌套(a);
console.log(result)
您可以使用
reduce()
方法并为此创建递归函数

var a=[{“id”:0,“name”:“Node 0”,“缩略图”:{“description”:“Random Picture”,“href”:“}”,parent:null},{“id”:1,“name”:“Node 1”,“缩略图”:{“description”:“other Random Picture”,“href”:“}”,“name”:“Node 2”,“缩略图”:{“description”:“a Picture Is Random”,“href”:“},”parent:null},{“id”:3,“name”:“Node 3”,“缩略图”:{”描述“:“图片,随机”,“href:”},“父项”:1}]
嵌套函数(arr,parentId){
返回arr.reduce(函数(r,e){
if(e.parent==parentId){
const children=嵌套(arr,e.id);
const clone=Object.assign({},e);
if(children.length)clone.children=children
r、 推送(克隆)
}
返回r;
}, [])
}
常量结果=嵌套(a);

console.log(结果)
我有一个JSON
-不,你有一个javascript对象…JSON从来没有
var x=
…JSON是一个对象的字符串表示形式…所以,你根本没有JSON…只是一个普通的javascript对象…
我正在尝试根据父对象和子对象关系来改革JSON结构。
-请显示实际的e预期的输出,不是只有你才能理解的模糊表示法。
我有一个JSON
-不,你有一个javascript对象…JSON从来没有
var x=
…JSON是一个对象的字符串表示法…所以,你根本没有JSON…只是一个普通的ol'javascript对象…
我正在尝试改革JSON的基于父级和子级关系的结构。
-请显示实际的预期输出,而不是只有您才能理解的模糊表示。请注意克隆是浅拷贝。请注意克隆是浅拷贝。