I've got a recursive array. So the array below can go deeper and deeper.
0: "1"
1: [
0: "2"
1: [
0: "3"
]
2: [
0: "4"
1: [
0: "5"
]
]
]
I want the output to be the path of all the values. So 123 and 1245.
How can this be done in a Javascript method?
You need a recursive method to flatten a recursive array.
Here's a pretty basic one:
var data = ["1",
[
"2",
[
"3"
],
[
"4",
[
"5"
]
]
]];
var flattened = [];
function flatten(data, outputArray) {
data.forEach(function (element){
if(Array.isArray(element)) {
flatten(element, outputArray);
} else {
outputArray.push(element);
}
});
}
flatten(data, flattened);
This should get you moving in the right direction. Good luck!
I am not sure, but what you have presented looks more like an object. In such case it is quite easy to traverse through the nested object, eg.
var object = { 0: "1",
1: {
0: "2",
1: {
0: "3"
},
2: {
0: "4",
1: {
0: "5"
}
}
}};
console.info(object);
function traverse(obj) {
obj.keys.forEach(function(key) {
if (typeof(obj[key]) === 'object') {
traverse(obj[key])
}
else {
//do something with the actual value
console.log(obj[key])
}
})
};
traverse(object)
Can you specify what did you mean with I want the output to be the path of all the values?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With