Reputation: 13
I am trying to map a complex object array document to a single level array. For example..
[{
name: 'birds',
references: [{ name: 'owl', value: 20 },
{ name: 'sparrow', value: 23 }],
identified: { created: '2014-02-02' }
}, {
name: 'animals',
references: [{ name: 'cat', value: 20 },
{ name: 'deer', value: 23 }],
identified: { created: '2014-02-02' }
}]
The objective is to turn the array into some thing like this regardless of the complexity
[{name: 'birds', references-owl: 20, references-sparrow: 23, identified-created: '2014-02-02'},
{name: 'animals', references-cat: 20, references-deer: 23, identified-created: '2014-02-02'}]
Basically, if loop through each item in array and then loop through each property.
If the property is an array, add property to parent object with key composed of the name property from the array and parent key value like 'references-owl' and value from the property. All other array objects can be ignored beyond first level.
If the property is an object, prefix the key with the parent property and add it to parent object. If a child array exists, repeat above.
Thanks in advance!!!
Upvotes: 0
Views: 1241
Reputation: 72857
A combination of .map()
and .reduce()
is exactly what you need here:
var data = [{
name: 'birds',
references: [{ name: 'owl', value: 20 },
{ name: 'sparrow', value: 23 }],
identified: { created: '2014-02-02' }
}, {
name: 'animals',
references: [{ name: 'cat', value: 20 },
{ name: 'deer', value: 23 }],
identified: { created: '2014-02-02' }
}];
var result = data.map(function(row){ // For each row in data.
// Set the static data in the result row
var reference = { name: row.name, 'identified-created': row.identified.created };
// Iterate over `row.references`, and add the current reference to the result.
row.references.reduce(function(previous, current){
previous['reference-' + current.name] = current.value;
return previous;
}, reference);
return reference;
});
console.log(result);
Upvotes: 1