I have the following array structure:
const values = [{
"region": "US", "content": "content 1", "value": "value1"
}, {
"region": "US", "content": "content 2", "value": "value2"
}, {
"region": "US", "content": "content 3", "value": "value3"
}, {
"region": "LA", "content": "content 4", "value": "value4"
}, {
"region": "LA", "content": "content 5", "value": "value5"
}, {
"region": "LA", "content": "content 6", "value": "value6"
}, {
"region": "LA", "content": "content 7", "value": "value7"
}]
and I am trying to transform it into the following – notice the region key is gone from the resulting object inside the output array:
const output = [{
"US": [
{"content": "content 1", "value": "value1"},
{"content": "content 2", "value": "value2"},
{"content": "content 3", "value": "value3"}
],
"LA": [
{"content": "content 4", "value": "value4"},
{"content": "content 5", "value": "value5"},
{"content": "content 6", "value": "value6"},
{"content": "content 7", "value": "value7"}
]
}]
So far this is what I have tried:
let outputValues = [];
values.forEach(currentElement => {
outputValues[currentElement.region].push(currentElement);
})
console.log(outputValues);
The above solution gives me the following error:
Uncaught TypeError: Cannot read properties of undefined (reading ‘push’)
Not sure why.
I have tried also:
# 1st option
outputValues[currentElement.region] = currentElement;
# 2nd option
outputValues[currentElement.region] = [];
outputValues[currentElement.region].push(currentElement);
But that adds only the last element from the main values array. What am I missing here?
>Solution :
If you do not want to keep the original objects, you could take the unwanted key as grouping value and delete this property while grouping.
const
values = [{ region: "US", content: "content 1", value: "value1" }, { region: "US", content: "content 2", value: "value2" }, { region: "US", content: "content 3", value: "value3" }, { region: "LA", content: "content 4", value: "value4" }, { region: "LA", content: "content 5", value: "value5" }, { region: "LA", content: "content 6", value: "value6" }, { region: "LA", content: "content 7", value: "value7" }],
result = Object.groupBy(values, o => {
const group = o.region;
delete o.region;
return group;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }