I have a javascript nested object as shown below :
input_data = {
"A1":{
"B1":{
"M1" : [
{"E1":"10","E2":"11"},
{"E1":"20","E2":"21"}
],
"M2":[
{"E1":"30","E2":"31"},
{"E1":"40","E2":"41"}
],
"M3":[
{"E1":"50","E2":"51"}
]
}
},
"A2":{
"B2":{
"M1": [
{"E1":"60","E2":"61"},
{"E1":"70","E2":"71"}
],
"M2":[
{"E1":"80","E2":"81"},
{"E1":"90","E2":"91"}
]
}
}
}
I need to extract all the items under "M1","M2","M3" into an array, that is , the output should be as shown below:
output_data = [
{"E1":"10","E2":"11"},
{"E1":"20","E2":"21"},
{"E1":"30","E2":"31"},
{"E1":"40","E2":"41"},
{"E1":"50","E2":"51"},
{"E1":"60","E2":"61"},
{"E1":"70","E2":"71"},
{"E1":"80","E2":"81"},
{"E1":"90","E2":"91"}
];
I could achieve this in the following way:
var output_data = [];
function traverse(obj) {
for (i in obj) {
if (!!obj[i] && typeof(obj[i])=="object") {
if (Array.isArray(obj[i])){
output_data = output_data.concat([], obj[i]);
}
traverse(obj[i] );
}
}
}
traverse(input_data);
console.log(output_data);
Is there a better way of extracting the child array items and merging into one?