The JSON data I am working on it
"data": [
{
"campaign_name": "Daily Shopping - [Reach Ad]",
"reach": "2365439",
"clicks": "43692",
"impressions": "4873908",
"actions": [
{
"action_type": "like",
"value": "1"
},
{
"action_type": "comment",
"value": "40"
}
],
"date_start": "2022-05-27",
"date_stop": "2022-06-03"
},
Here is the code I have used but it is wrong.
result = arr.reduce((r,o) => {r[o.action_type] = o.value; return r; }, {});
Output should be like the following way
"data": [
{
"campaign_name": "Daily Shopping - [Reach Ad]",
"reach": "2365439",
"clicks": "43692",
"impressions": "4873908",
"like": "1",
"comment: "40"
}
This can be achieved with Object.fromEntries and spread syntax in object literals:
const arr = [{"campaign_name": "Daily Shopping - [Reach Ad]","reach": "2365439","clicks": "43692","impressions": "4873908","actions": [{"action_type": "like","value": "1"},{"action_type": "comment","value": "40"}],"date_start": "2022-05-27","date_stop": "2022-06-03"},];
const result = arr.map(({actions, ...rest}) => ({
...rest,
...Object.fromEntries(actions.map(({action_type, value}) =>
[action_type, value]
))
}));
console.log(result);
Below is an implementation using Object.entries() and reduce()
const raw_data = `{
"data": [
{
"campaign_name": "Daily Shopping - [Reach Ad]",
"reach": "2365439",
"clicks": "43692",
"impressions": "4873908",
"actions": [
{
"action_type": "like",
"value": "1"
},
{
"action_type": "comment",
"value": "40"
}
],
"date_start": "2022-05-27",
"date_stop": "2022-06-03"
}
]
}`;
const data = JSON.parse(raw_data).data;
const processedData = Object.entries(data[0]).reduce(
(accumulator, [currentProperty, currentValue]) => {
if (currentProperty !== "actions") {
if (!currentProperty.includes("date"))
accumulator[currentProperty] = currentValue;
} else {
currentValue.forEach(
(action) => (accumulator[action.action_type] = action.value)
);
}
return accumulator;
},
{}
);
console.log(processedData);
Your code is almost correct. As you can see, only the initial argument passed to the reducer needs to be modified. The modification can be applied in situ.
Code
let s_x = `{
"data": [
{
"campaign_name": "Daily Shopping - [Reach Ad]",
"reach": "2365439",
"clicks": "43692",
"impressions": "4873908",
"actions": [
{
"action_type": "like",
"value": "1"
},
{
"action_type": "comment",
"value": "40"
}
],
"date_start": "2022-05-27",
"date_stop": "2022-06-03"
}
]
}`
, x = JSON.parse(s_x)
;
x.data.forEach ( po_orig => {
let o_transformed = po_orig.actions.reduce ((r,o) => {
r[o.action_type] = o.value; return r;
}, po_orig) // Note: po_orig instead of {}
;
delete po_orig['actions'];
});
console.log(`new data: `, x);