i具有查看对象质量并将新属性推入新属性的功能。我想将当前对象的级别保存为新对象的属性。
(
数据[0],数据[1],..-级别1
数据[0] .childs [0],数据[1] .childs [0],..-level2
...
)
但是我的代码中有两个交叉链接的函数,我为此大吃一惊。
var data = [
{a1: 1, a2: 2, childs: [{a1: 12, a2: 13, childs: [{a1: "test114", childs:[]}]}, {a1: 114, a2: 115, childs: [{a1:1116, a2: 1117, childs: []}]}] },
{a1: 3, a2: 4, childs: [{a1: 22, a2: 23, childs: []}, {a1: 224, a2: 223, childs: [{a1:2221, a2: 2222, childs: []}]}] },
{a1: 5, a2: 6, childs: [{a1: 32, a2: 33, childs: []}] },
{a1: 7, a2: 8, childs: []}
];
var mass = [];
var newarray = [];
var level = 1;
function go() {
returnObject(data, mass);
console.log(mass);
}
function returnObject(obj, arr) {
obj.forEach(function(item) {
returnObject2(item, arr);
});
}
function returnObject2(obj, arr){
console.log(obj);
console.log(arr)
if(Array.isArray(obj)){
return
}
if (obj.childs.length > 0){
arr.push({new:obj.a1, childs: obj.childs, level: level});
level+=1;
return returnObject(obj.childs, arr);
}
else {
return arr.push({new:obj.a1, childs: [], level: level});
}
}
<button onClick=go()> go!</button>
答案 0 :(得分:0)
不要将level
设置为全局变量,将其传递出去!
function returnObject(obj, arr, level) {
obj.forEach(function(item) {
returnObject2(item, arr, level + 1);
});
}
function returnObject2(obj, arr, level){
...
return returnObject(obj.childs, arr, level + 1);
etc