I have this JSON and I need to group in a new object by key:
[
{
"product": "name 1",
"price": "3000",
"inspection": false,
},
{
"product": "name 2",
"price": "1000",
"inspection": true,
},
{
"product": "name 3",
"price": "5000",
"inspection": false,
},
]
Expected Final Result:
{
"product": ["name 1", "name 2", "name 3"],
"price": ["3000", "1000", "5000"],
"inspection": [false, true, false]
}
I tried to use -> for, foreach <- but not getting a good/optimum result. I also considered using reduce but I couldn't get it to work.
let data = [
{
"product": "name 1",
"price": "3000",
"inspection": false,
},
{
"product": "name 2",
"price": "1000",
"inspection": true,
},
{
"product": "name 3",
"price": "5000",
"inspection": false,
},
];
let output = Object.fromEntries(
Object.keys(data[0]).map(k =>
[k, data.map(d => d[k])]
)
);
console.log(output);
For objects of any shape, this'll group items under any key:
const arr = [
{ product: "name 1", price: 3000, inspection: false },
{ product: "name 2", price: 1000, inspection: true },
{ product: "name 3", price: 5000, inspection: false },
]
const groups = arr.reduce((groups, obj) =>
Object.entries(obj).reduce((groups, [key, val]) => (
{ ...groups, [key]: (groups[key]??[]).concat(val) }
), groups)
, {})
console.log(groups)
Which keys get grouped may be changed by filtering the result of Object.entries(obj) by key.
Presented below is one possible way to achieve the desired objective.
Code Snippet
// one possible method to transform given array
const myTransform = arr => (
arr.reduce(
(acc, { product, price, inspection }) => (
(acc.product ??= []).push(product),
(acc.price ??= []).push(name),
(acc.inspection ??= []).push(inspection),
acc
),
{}
)
);
// using a simple for loop:
const myTransform2 = arr => {
// initialize result "res" as empty object
const res = {};
// iterate over each elt in array "arr"
for ({ product, price, inspection } of arr) {
// if res has no key product, add one with value as empty array
// push the "product" to the above key
(res.product ??= []).push(product);
// same logic for price
(res.price ??= []).push(name);
// same for inspection
(res.inspection ??= []).push(inspection);
};
// return the result
return res;
};
const dataArr = [{
"product": "name 1",
"price": "3000",
"inspection": false,
},
{
"product": "name 2",
"price": "1000",
"inspection": true,
},
{
"product": "name 3",
"price": "5000",
"inspection": false,
},
];
console.log(
'transformed array:\n',
myTransform(dataArr)
);
console.log(
'transformed array using for loop:\n',
myTransform2(dataArr)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Comments added to the snippet above.