[英]How to loop through array and assign every item a value without loop?
I have an array of object like so:我有一个 object 数组,如下所示:
let data = [{Date : null, id: null}, {Date : null, id: null}, {Date : null, id: null}]
And i need to assign every Date property a value.我需要为每个 Date 属性分配一个值。 I did it with a loop
我用循环做到了
let dates = ['2022-01-01','2022-02-02','2020-02-03']
for (let i=0; i<dates.length; i++) {
data[i].Date = dates[i]
}
But i was wondering is it possible to do with one line?但我想知道是否可以用一条线做? I was trying to use something like this, but it didn't work.
我试图使用这样的东西,但它没有用。
data.map((i)=>{
data[i].Date = dates[i]
})
Because i
doenst hold index but a value.因为
i
不持有索引而是一个值。 Is it possible to use i
as index iterator in map?是否可以在 map 中使用
i
作为索引迭代器?
map()
creates a new array, if you want to alter data
, use forEach
so you can get the current index to find the desired value in dates
map()
创建一个新数组,如果要更改data
,请使用forEach
以便获取当前索引以在dates
中找到所需的值
data.forEach((d, i) => d.Date = dates[i]);
let data = [{Date: null, id: null}, {Date: null, id: null}, {Date: null, id: null}]; let dates = ['2022-01-01','2022-02-02','2020-02-03']; data.forEach((d, i) => d.Date = dates[i]); console.log(data);
You can do it more functional, in a cleaner way by using map...您可以通过使用 map 以更简洁的方式实现它的功能性更强...
let data = [{Date: null, id: null}, {Date: null, id: null}, {Date: null, id: null}]; let dates = ['2022-01-01','2022-02-02','2020-02-03']; const newData = data.map((a, i) => ({Date: dates[i], id: a.id})); console.log(newData);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.