I'm working on flatten array function. It takes an input like this
const input = [
{
"value": "value0",
"children": []
},
{
"value": "value1",
"children": [
{
"value": "value2",
"children": [
{
"value": "value3",
"children": []
}
]
},
{
"value": "value4",
"children": []
}
]
},
{
"value": "value5",
"children": []
},
{
"value": "value6",
"children": []
}
];
and return an array
[
{"value":"value0"},
{"value":"value1"},
{"value":"value2"},
{"value":"value3"},
{"value":"value4"},
{"value":"value5"},
{"value":"value6"}
]
I have solved this problem. Here is my former wrong code and I was trying to debug it
function flatArray(input) {
if(input.length === 0) return [];
let res = [];
input.forEach(i => {
for(let key of Object.keys(i)) {
if(key === 'value') {
res.push({[key]: i[key]});
} else {
const arr = flatArray(i[key]);
res.concat(arr);
console.log(res);
}
}
});
return res;
}
PS: It's wrong because the misuse of concat
The output is weird. I got
I'm wondering why the first three are type of object? And why, like the first output, can get an array with 4 elements instead of getting an array with only {value: value0}?
I guess it has something to do with closures but I can't explain this thing. Can anyone help me?