gpt4 book ai didi

javascript - 将特定数组元素复制到现有对象(覆盖)

转载 作者:行者123 更新时间:2023-11-29 16:38:51 25 4
gpt4 key购买 nike

我有以下对象

var obj1 = 
[
{
"id": 1373744172,
"name": "Run",
"distance": 6051.8,
"date": "2018-01-24T16:43:09Z",
},
{
"id": 1370355715,
"name": "Swim",
"distance": 1043,
"date": "2018-01-22T21:10:28Z",
}
]

var dest =
[
{title: "Placeholder", body: "1900-01-01T00:00:00Z"}
]

我正在尝试基于 obj1 覆盖 dest,所以我最终应该得到

[
{title: "Run", body: "2018-01-24T16:43:09Z"},
{title: "Swim", body: "2018-01-22T21:10:28Z"}
]

我已经研究过 Object.assign 和 for-in 循环,但我还没有找到正确的方法。例如

var obj1 = 
[
{
"id": 1373744172,
"name": "Run",
"distance": 6051.8,
"date": "2018-01-24T16:43:09Z",
},
{
"id": 1370355715,
"name": "Swim",
"distance": 1043,
"date": "2018-01-22T21:10:28Z",
}
]

var dest =
[
{title: "Placeholder", body: "1900-01-01T00:00:00Z"}
]

Object.assign(dest, {title: obj1.name, body: obj1.date});

console.log(JSON.stringify(dest));

我确信这个问题之前一定有人问过并回答过,但我似乎没有使用正确的术语进行搜索!

最佳答案

您不需要Object.assign,使用array.prototype.map来转换数组的每个元素:

var obj1 = 
[
{
"id": 1373744172,
"name": "Run",
"distance": 6051.8,
"date": "2018-01-24T16:43:09Z",
},
{
"id": 1370355715,
"name": "Swim",
"distance": 1043,
"date": "2018-01-22T21:10:28Z",
}
];

var dest = obj1.map(e => ({title: e.name , body: e.date}));

console.log(dest);

关于javascript - 将特定数组元素复制到现有对象(覆盖),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48460109/

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