将一个对象数组中的一个对象扁平化到一个对象数组中



我有一个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"
}
]
},
]

我试过使用数组。映射方法,使用如下所示;

const locations = locations.map((location) =>
location.services.nodes.map((service) => service)
);

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; }

最新更新