gpt4 book ai didi

javascript - 从现有 JSON 数组的嵌套键/值创建一个新的 JSON 数组

转载 作者:行者123 更新时间:2023-11-30 14:26:40 25 4
gpt4 key购买 nike

我有一个对象数组,它们的结构总是这样的:

var initialJSON = [  
{
"id":"01",
"name":"Jane",
"project":{
"title":"Alpha",
"description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"city":"New York"
},
"dateCreated":"2018-04-28 04:11:16 UTC"
},
{
"id":"02",
"name":"Sarah",
"project":{
"title":"Beta",
"description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"city":"London"
},
"dateCreated":"2018-04-28 04:11:29 UTC"
},
{
"id":"03",
"name":"Mia",
"project":{
"title":"Gamma",
"description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"city":"Paris"
},
"dateCreated":"2018-04-28 04:11:29 UTC"
}
];

我的目标是创建一个新的对象数组,其中仅包含每个项目项目的键/值。基本上从每个项目中删除所有其他数据(包括父键“project”)。

最终结果是这样的:

var formattedJSON = [
{
"title":"Alpha",
"description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"city":"New York"
},
{
"title":"Beta",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"city":"London"
},
{
"title":"Gamma",
"description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"Paris"
}
]

我很难找到循环遍历数据并获得正确结果的方法。我知道已经发布了类似的问题,但似乎没有从内部键的嵌套键/值中创建一个新数组。

最佳答案

您可以使用 Array#map()为此,通过将数组的每个元素分配给它的 project 属性:

let initialJSON=[{"id":"01","name":"Jane","project":{"title":"Alpha","description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit","city":"New York"},"dateCreated":"2018-04-28 04:11:16 UTC"},{"id":"02","name":"Sarah","project":{"title":"Beta","description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit","city":"London"},"dateCreated":"2018-04-28 04:11:29 UTC"},{"id":"03","name":"Mia","project":{"title":"Gamma","description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit","city":"Paris"},"dateCreated":"2018-04-28 04:11:29 UTC"}];

let result = initialJSON.map(element => element.project);

console.log(result)

关于javascript - 从现有 JSON 数组的嵌套键/值创建一个新的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51813679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com