我想遍历对象数组,并将所有1 st 和2 nd 值从上到下依次放入数组。
返回的数组应该包含31个元素,但是我在下面编写的解决方案返回array.length == 29
。我找不到循环在哪里丢失值。
let userTree = [{
"username": "USER1",
"income": 1000,
"st1": {
"username": "USER2",
"income": 2000,
"st1": {
"username": "USER4",
"income": 4564560,
"st1": '',
"nd2": {
"username": "USER7",
"income": 4564560,
"st1": {
"username": "USER10",
"income": 4564560,
"st1": '',
"nd2": ''
},
"nd2": {
"username": "USER11",
"income": 4564560,
"st1": '',
"nd2": ''
}
}
},
"nd2": ''
},
"nd2": {
"username": "USER3",
"income": 2001,
"st1": {
"username": "USER5",
"income": 40,
"st1": '',
"nd2": ''
},
"nd2": {
"username": "USER6",
"income": 4564560,
"st1": {
"username": "USER8",
"income": 40,
"st1": '',
"nd2": {
"username": "USER12",
"income": 40,
"st1": '',
"nd2": ''
}
},
"nd2": {
"username": "USER9",
"income": 40,
"st1": {
"username": "USER13",
"income": 40,
"st1": '',
"nd2": ''
},
"nd2": {
"username": "USER14",
"income": 40,
"st1": '',
"nd2": ''
}
}
}
}
}];
let userArray = [userTree[0]];
let counter = 1;
let rowArray = [];
let counterArr = [];
let usersRow = '';
let rowHTML = '';
let treeRow = '';
const getUsers = (users = {}) => {
Object.entries(users).forEach(user => {
let key = user[0];
let value = user[1];
if (typeof value == 'object') {
userArray.push(value);
} else if (value == '') {
userArray.push(value);
}
});
};
const getSubUsers = (subUser = {}) => {
for (let i = 0; i <= userArray.length; i++) {
let lastUser = userArray[i];
getUsers(lastUser);
}
};
getSubUsers(userArray);
console.log(userArray.length);
console.log(userArray);