我想在JavaScript中的数组上添加新值。数组是这样的:
[
0: { Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003" },
1: { Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003" }
]
这是一个简单的数组,我的数组更大,值更多。我想添加这样的新值:
[
0: { Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003",
SecondTime: "2020-06-08T11:12:03.003" },
1: { Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003",
SecondTime: "2020-06-08T11:12:03.003" }
]
我知道有很多类似的问题,但是我找不到解决问题的方法。
使用foreach
const data = [
{ Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003" },
{ Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003" }
]
data.forEach(i=>{
i.SecondTime = "2020-06-08T11:12:03.003"
});
console.log(data)
使用reduce
:
const data = [
{ Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003" },
{ Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003" }
]
var res = data.reduce((acc, elem)=>{
elem.secondtime = elem.Time;
acc.push(elem);
return acc
},[]);
console.log(res)