我有一个排序的二维数组作为输入。我需要以相同的结构获得一组嵌套对象,如下所示。如何获得预期的输出?
input = [
["1", "2", "3", "4", "5", "6", "7", "8"],
["1", "2", "3", "4", "5", "6", "7", "9"],
["cat", "accessories", "clothes"],
["cat", "food", "dry"],
["cat", "food", "wet"],
["dog", "drinks"],
["dog", "food"]];
这是我尝试过的:
var output = [];
input.forEach((v, i) => {
if (i !== 0){
var temp_obj = {};
for(let j=0; j<v.length; j++){
if (input[i-1][j] === v[j]){
temp_obj[input[i-1][j]] = [];
}else if (!_.isEmpty(temp_obj) && typeof(input[i-1][j]) !== 'undefined'){
console.log('this is it ', temp_obj)
}
}
if (!_.isEmpty(temp_obj)){
output.push(temp_obj);
}
}
})
console.log(output)
预期产出
output = [{
"1": [{
"2": [{
"3": [{
"4": [{
"5": [{
"6": [{
"7": [{
"8": []
}, {
"9": []
}]
}]
}]
}]
}]
}]
}]
},
{
"cat": [{
"accessories": [{
"clothes": []
}]
}, {
"food": [{
"dry": []
}, {
"wet": []
}]
}]
},
{
"dog": [{
"food": []
}, {
"drinks": []
}]
}
]