Reputation: 33
I am able to get all unique properties from an array like this,
var array = [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"car": true
}, {
"firstName": "Peter",
"lastName": "Jones"
}];
var result = [];
array.reduce( function(pre, item) {
Object.keys(item).forEach(function(i){
if (result.indexOf(i) === -1){
result.push(i);
}
});
});
console.log(result);
However now I need this output,
[{
"firstName":"John, Anna, Peter",
"car": "true",
"lastName": "Doe, Jones"
}]
but I am not sure how to ?
Upvotes: 0
Views: 56
Reputation: 34556
Various ways. Here's one:
//get unique properties - hence Set, not array, so dups are omitted
let props = new Set(array.map(obj => Object.keys(obj)).flat());
//get non-falsy value for each prop type, as an array
let vals = [...props].map(prop => array.map(obj => obj[prop]).filter(a => a).join(', '));
//merge the two via Object.fromEntries()
let final = Object.fromEntries.call(null, [...props].map((prop, i) => [prop, vals[i]]));
Upvotes: 1
Reputation: 14891
You could achieve that by having a lookup object that store all values for a property. Then manipulate that object by joining all occurences
Below snippet could help you
var array = [
{
firstName: "John",
lastName: "Doe",
},
{
firstName: "Anna",
car: true,
},
{
firstName: "Peter",
lastName: "Jones",
},
]
var lookup = {}
var result = {}
array.forEach((obj) => {
Object.entries(obj).forEach(([key, val]) => {
if (!lookup[key]) {
lookup[key] = [val]
} else {
lookup[key].push(val)
}
})
})
Object.entries(lookup).forEach(([key, val]) => {
result[key] = val.join(', ')
})
console.log(result)
Upvotes: 0