I am trying to group an array of objects like the below using JavaScript.
const array = [
{ 'red': 50 , 'green':99 , 'blue': 66},
{'blue':65, 'red': 88 },
{ 'green':9 , 'blue': 6},
{ 'red': 650 , 'green':959 , 'blue': 663},
];
and expecting the below result,
{
red: [50, 88, 650],
green: [99,9,959],
blue: [66,65, 6, 663]
}
Can someone help me?
Thanks in advance!.
CodePudding user response:
You can try the below approach to do so. Hope it helps
Loop through the array
and it's items. If the key already exists inside the outputObj
object push the new value into the respective array, else simply create a new array with that key and value (outputObj[key] = [item[key]]
).
const array = [{
'red': 50,
'green': 99,
'blue': 66
},
{
'blue': 65,
'red': 88
},
{
'green': 9,
'blue': 6
},
{
'red': 650,
'green': 959,
'blue': 663
},
];
const outputObj = {};
array.forEach(item => {
Object.keys(item).forEach(key => {
if (key in outputObj) {
outputObj[key].push(item[key])
} else {
outputObj[key] = [item[key]]
}
})
})
console.log(outputObj)
CodePudding user response:
const red = Object.values(array[0]);
const blue = Object.values(array[1]);
const green = Object.values(array[2]);
const colors = { red, green, blue }
CodePudding user response:
This piece of code will fill the result object grouping values coming from the same key in the array variable:
var result = {};
array.forEach(
item => Object.keys(item).forEach(
key => {
if (result[key] === undefined) result[key] = [];
result[key].push(item[key]);
}
)
)
CodePudding user response:
const array = [
{ 'red': 50 , 'green':99 , 'blue': 66},
{'blue':65, 'red': 88 },
{ 'green':9 , 'blue': 6},
{ 'red': 650 , 'green':959 , 'blue': 663},
];
function group(array, result = {}) {
array.forEach(object => {
Object.keys(object).forEach(key => {
if(!result[key]) {
result[key] = [object[key]];
return;
}
result[key].push(object[key]);
});
});
return result;
}
const result = group(array);
console.log(result);