I am trying to find a way to denormalize an array of objects in JavaScript to get a set of arrays. I need this structure for a table (denormalized dataset).
So, given the input:
var data = [
{ v1: 1, v2: [ { a: 1 }, { a: 2 } ] },
{ v1: 2, v2: [ { a: 3 }, { a: 4 } ], v3: 5 },
];
I need a structure like
var data2 = [
{ v1: 1, v2_a: 1 },
{ v1: 1, v2_a: 2 },
{ v1: 2, v2_a: 3, v3: 5 },
{ v1: 2, v2_a: 4, v3: 5 }
];
The recursive path.
My first attempt was to do a full depth scan scan by adding properties to a temporary variable:
var result = [];
function aArray(data) {
for(var i = 0; i < data.length; i++){
var temp = {};
for(var prop in data[i]){
var val = data[i][prop];
if( Object.prototype.toString.call( val ) === '[object Array]' ) {
aArray(val);
}else{
temp[prop] = val;
}
}
result.push(temp);
}
}
But something is not working properly
source
share