For a react project I need to simplify an array of objects.
I've an array of objects coming from wp rest api axios request. Inside objects there are objects. I would like to "remove" this nested object in order to have this :
[
{
"id": 101,
"title": "CTC20180018",
"fielda": "valuea",
"fieldb": "valueb",
"fieldc": "valuec"
},
{
"id": 102,
"title": "D2021063365",
"fielda": "valuea",
"fieldb": "valueb",
"fieldc": "valuec"
},
...
]
What is the best solution ? .map()
the array and use destructuring
?
The original array :
[
{
"id": 101,
"title": {
"rendered": "CTC20180018"
},
"acf": {
"fielda": "valuea",
"fieldb": "valueb",
"fieldc": "valuec"
}
},
{
"id": 102,
"title": {
"rendered": "D2021063365"
},
"acf": {
"fielda": "valuea",
"fieldb": "valueb",
"fieldc": "valuec"
}
},
...
]
CodePudding user response:
Try something like below using map
, Object destructuring and spread operator
const data = [{
"id": 101,
"title": {
"rendered": "CTC20180018"
},
"acf": {
"fielda": "valuea",
"fieldb": "valueb",
"fieldc": "valuec"
}
},
{
"id": 102,
"title": {
"rendered": "D2021063365"
},
"acf": {
"fielda": "valuea",
"fieldb": "valueb",
"fieldc": "valuec"
}
}
]
const result = data.map(({
id,
title,
acf
}) => ({
id: id,
title: title.rendered,
...acf
}));
console.log(result);