Reputation: 31
I'm trying to find a way to denormalize an array of objects in JavaScript to obtain a set of arrays. I need that structure for a table (denormalized set of data).
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 }
];
Recursive way.
My first attempt is to do a full scan search in depth adding the properties in a temporal 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 doesn't work as expected
Upvotes: 3
Views: 1247
Reputation: 3645
You can try this solution
var data = [
{ v1: 1, v2: [ { a: 1 }, { a: 2 } ] },
{ v1: 2, v2: [ { a: 3 }, { a: 4 } ], v3: 5 },
];
function is_a(a){
return (typeof a == "object") && (a instanceof Array);
}
function extend(a, b){
for(var i in b){
a[i] = b[i];
}
return a;
}
Now main logic here:
var p = data.map(function(item){
var output = {};
var list = [];
for(var i in item){
if(is_a(item[i])){
for(var j = 0; j < item[i].length; j++){
for(var z in item[i][j]){
var k = {}; k[i + "_" + z] = item[i][j][z];
list.push(k);
}
}
}
else{
output[i] = item[i];
}
}
for(var i = 0; i < list.length; i++){
list[i] = extend(list[i], output);
}
console.log(list);
});
Output: First
0: Object v1: 1 v2_a: 1
1: Object v1: 1 v2_a: 2
Second
0: Object v1: 2 v2_a: 3 v3: 5
1: Object v1: 2 v2_a: 4 v3: 5
Try demo
Upvotes: 1