[英]Flattening and object with an array of objects in to an array of objects
我有一個 GraphQL 端點,它以以下格式返回數據(稱為位置);
[
{
"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"
}
]
},
},
]
我想做的是“扁平化”它,以便服務成為對象數組並且節點不再存在。 所以預期的結果是;
[
{
"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"
}
]
},
]
我嘗試過使用 array.map 方法來執行以下操作;
const locations = locations.map((location) =>
location.services.nodes.map((service) => service)
);
Map 數組到一個新的數組,其中services.nodes
數組設置為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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.