gpt4 book ai didi

javascript - 如何展平嵌套对象?

转载 作者:行者123 更新时间:2023-12-01 00:00:13 28 4
gpt4 key购买 nike

我有以下嵌套对象:

[
{
"id": "b2dgd67e7e7",
"fields": {
"task1": "task 1",
"task2": "task 2"
}
},
{
"id": "b2dgd67e7e8",
"fields": {
"task1": "task 3",
"task2": "task 4"
}
}
]

我想将其展平为以下格式:...................................... ........

[
{

"fields": {
"task1": "task 1",
"task2": "task 2",
"id": "b2dgd67e7e7",
}
},
{

"fields": {
"task1": "task 3",
"task2": "task 4",
"id": "b2dgd67e7e8",
}
}
]

最佳答案

您可以使用.map()在您的数组上构建一个新的映射对象数组。要映射每个对象,您可以 destructure对象中的 idfields 属性,然后返回一个新对象,其中包含您的 fields 属性以及 的原始内容>fields 对象值以及其余外部属性(例如 id):

const arr = [{ "id": "b2dgd67e7e7", "fields": { "task1": "task 1", "task2": "task 2" } }, { "id": "b2dgd67e7e8", "fields": { "task1": "task 3", "task2": "task 4" } } ];

const flattenToKey = (arr, key) =>
arr.map(({[key]: k, ...r}) => ({[key]: {...k, ...r}}));

const res = flattenToKey(arr, 'fields');
console.log(res);

关于javascript - 如何展平嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60783309/

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