JavaScript 硬代码循环问题。设置 grandchildren 到 children 到 parent
JavaScript hard code to loop problem. Setting grandchildren to children to parent
我认为很简单的事情结果却让我头疼了好几天。我可以让它工作 hard-coding 但不能让它循环工作。这就是我的 hard-coded.
let vt = [{animal:"dog"},{color:"green"},{tail:"curly"}];
vt[0]["children"]={pupname:"harry",pupcolor:"red"}
vt[0]["children"]["children"]={pupname:"joe",pupcolor:"brown"}
vt[0]["children"]["children"]["children"]={pupname:"itchy",pupcolor:"black"}
console.log(JSON.stringify(vt));
这会给我我想要的。
[{
"animal": "dog",
"children": {
"pupname": "harry",
"pupcolor": "red",
"children": {
"pupname": "joe",
"pupcolor": "brown",
"children": {
"pupname": "itchy",
"pupcolor": "black"
}
}
}
}, {
"color": "green"
}, {
"tail": "curly"
}]
这是一个简化版本,数组中可以有很多 objects。我无法让它循环工作。 children 键的数量不断增加是我的问题,或者我可能已经偏离轨道了。欢迎任何指点
你可以做到:
const vt = [ { animal: 'dog' }, { color: 'green' }, { tail: 'curly' } ];
[ { pupname:'harry', pupcolor:'red' }
, { pupname:'joe', pupcolor:'brown' }
, { pupname:'itchy', pupcolor:'black' }
].reduce((a,c)=>a.children = c, vt[0]);
console.log( vt );
.as-console-wrapper {max-height: 100%!important;top:0 }
我认为很简单的事情结果却让我头疼了好几天。我可以让它工作 hard-coding 但不能让它循环工作。这就是我的 hard-coded.
let vt = [{animal:"dog"},{color:"green"},{tail:"curly"}];
vt[0]["children"]={pupname:"harry",pupcolor:"red"}
vt[0]["children"]["children"]={pupname:"joe",pupcolor:"brown"}
vt[0]["children"]["children"]["children"]={pupname:"itchy",pupcolor:"black"}
console.log(JSON.stringify(vt));
这会给我我想要的。
[{
"animal": "dog",
"children": {
"pupname": "harry",
"pupcolor": "red",
"children": {
"pupname": "joe",
"pupcolor": "brown",
"children": {
"pupname": "itchy",
"pupcolor": "black"
}
}
}
}, {
"color": "green"
}, {
"tail": "curly"
}]
这是一个简化版本,数组中可以有很多 objects。我无法让它循环工作。 children 键的数量不断增加是我的问题,或者我可能已经偏离轨道了。欢迎任何指点
你可以做到:
const vt = [ { animal: 'dog' }, { color: 'green' }, { tail: 'curly' } ];
[ { pupname:'harry', pupcolor:'red' }
, { pupname:'joe', pupcolor:'brown' }
, { pupname:'itchy', pupcolor:'black' }
].reduce((a,c)=>a.children = c, vt[0]);
console.log( vt );
.as-console-wrapper {max-height: 100%!important;top:0 }