I'm starting a new project in React and my API returns me a JSON where the format is not what I want for meetings. I've tried to use destructuring and Object.entries
. What I have:
{
"meetings": [
{
"room1": DC13,
"room2": AP47,
}
],
"teachers": [
{
"name: "Patrick",
"speciality":"Math"
},
...
],
"alumni": [
{
"firstName": "Joe",
"lastName":"Luis"
},
...
]
}
What I want:
{
"meetings": [
{
"name": room1,
"location": DC13,
},
{
"name": room2,
"location": AP47,
},
],
"teachers": [
{
"name: "Patrick",
"speciality":"Math"
},
...
],
"alumni": [
{
"firstName": "Joe",
"lastName":"Luis"
},
...
]
}
What I've tried but not working:
const data= {meetings, teachers, alumni}
const newData = Object.entries(meetings).reduce((acc,name,location])=>acc.concat({name,location}),[]))
and then use this newData for manipulation after.
CodePudding user response:
This gets you the desired output. It maps it each meeting and restructures the object by mapping its entry into a new object with the name
and location
keys.
const data = {
meetings: [
{
room1: "DC13",
room2: "AP47",
}
],
teachers: [
{
name: "Patrick",
speciality: "Math",
},
],
alumni: [
{
firstName: "Joe",
lastName: "Luis",
},
],
}
const newData = {
...data,
meetings: data.meetings.map(meeting =>
Object.entries(meeting)
.map(([name, location]) =>
({name, location})
)
)
}
console.log(newData);
CodePudding user response:
It seems that using map
here would be cleaner than reduce
, so here's a working solution using map
.
const data = { meetings, teachers, alumni };
data.meetings = Object.entries(data.meetings[0]).map(([key, value]) => ({
"name": key,
"location": value,
}))