My array consists of objects structured like this:
let array = [{
"Age": 20,
"Name": "Kevin"
}, {
"Age": 15,
"Name": "Alfred"
}, {
"Age": 30,
"Name": "Joe"
}];
I am aiming to transform it into an object with combined values like this:
{
"Age": '20, 15, 30',
"Name": 'Kevin, Alfred, Joe'
}
When attempting the following reduce function:
let r = array.reduce(function(pV, cV) {
Object.keys(cV).map(function(key){
pV[key] = (pV[key] || [])concat(cV[key]);
});
return pV;
},{});
console.log(r); // { "Age": [20, 15, 30], "Name": ['Kevin', 'Alfred', 'Joe'] }
Alternatively, I tried another approach:
let r = array.reduce(function(pV, cV) {
Object.keys(cV).map(function(key){
pV[key] = (pV[key] || '') + ', ' + cV[key];
});
return pV;
},{});
console.log(r); // { "Age": ', 20, 15, 30', "Name": ', Kevin, Alfred, Joe' }
I'm uncertain which method will give me the desired outcome. Any suggestions on how to achieve my goal?