I have a GraphQL endpoint that returns data (called locations) in the following format;
[
{
"name": "Location 1",
"description": "-",
"state": "Georgia",
"address": "Kennesaw, GA 30144",
"services": {
"nodes": [
{
"id": "cG9zdDo0OQ==",
"name": "Window Cleaning",
"color": "#00A7E3"
}
]
},
},
{
"name": "Location 2",
"description": "-",
"state": "California",
"address": "Los Angeles, 90016",
"services": {
"nodes": [
{
"id": "cG9zdDo1Mg==",
"name": "Large Project Waterproofing",
"color": "#00668A"
},
{
"id": "cG9zdDo1MA==",
"name": "Surfaces, Stone & Metal Refinishing",
"color": "#333333"
},
{
"id": "cG9zdDo0OQ==",
"name": "Window Cleaning",
"color": "#00A7E3"
}
]
},
},
]
What I would like to do is "flatten" it so that service becomes the array of objects and nodes is no longer there. So the expected result would be;
[
{
"name": "Location 1",
"description": "-",
"state": "Georgia",
"address": "Kennesaw, GA 30144",
"services": [
{
"id": "cG9zdDo0OQ==",
"name": "Window Cleaning",
"color": "#00A7E3"
}
]
},
{
"name": "Location 2",
"description": "-",
"state": "California",
"address": "Los Angeles, 90016",
"services": [
{
"id": "cG9zdDo1Mg==",
"name": "Large Project Waterproofing",
"color": "#00668A"
},
{
"id": "cG9zdDo1MA==",
"name": "Surfaces, Stone & Metal Refinishing",
"color": "#333333"
},
{
"id": "cG9zdDo0OQ==",
"name": "Window Cleaning",
"color": "#00A7E3"
}
]
},
]
I have tried looking at using the array.map method to do this with something like the following;
const locations = locations.map((location) =>
location.services.nodes.map((service) => service)
);
Map the array to a new one where the services.nodes
array is set into services
const newLocations = locations.map(({ services: { nodes }, ...location }) => ({
...location,
services: nodes,
}));
const locations = [{"name":"Location 1","description":"-","state":"Georgia","address":"Kennesaw, GA 30144","services":{"nodes":[{"id":"cG9zdDo0OQ==","name":"Window Cleaning","color":"#00A7E3"}]}},{"name":"Location 2","description":"-","state":"California","address":"Los Angeles, 90016","services":{"nodes":[{"id":"cG9zdDo1Mg==","name":"Large Project Waterproofing","color":"#00668A"},{"id":"cG9zdDo1MA==","name":"Surfaces, Stone & Metal Refinishing","color":"#333333"},{"id":"cG9zdDo0OQ==","name":"Window Cleaning","color":"#00A7E3"}]}}]; const newLocations = locations.map(({ services: { nodes }, ...location }) => ({...location, services: nodes, })); console.log(newLocations);
.as-console-wrapper { max-height: 100%;important; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.