我有以下对象
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));

我确定之前一定要问过并回答过,但我似乎没有用正确的条款进行搜索!
答案 0 :(得分:5)
您不需要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);
答案 1 :(得分:0)
要保持相同的数组实例(如注释中所述)Array.splice
可以与Array.map
结合使用以转换新元素。但是splice将新元素作为附加参数,因此需要对调用splice
有点聪明:
let args = [0, dest.length].concat(obj1.map(e=>({title: e.name, body: e.date})));
dest.splice.apply(dest, args);