简体   繁体   English

如何循环遍历数组并为每个项目分配一个没有循环的值?

[英]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.

相关问题 为没有循环的数组中的每个对象赋值 - Assign a value to every object in an array without loop Javascript:如何每秒循环遍历每个数组的项目 - Javascript: How to loop through every array's item every second 通过循环将值分配给数组索引 - Assign value to array indexes through loop 我如何一次遍历2个数组并将数组中的颜色分配给另一个数组的每个值 - How can i loop through 2 arrays at once and assign colours from array to each value of the other array 循环遍历数组,将每个值分配给Javascript / Jquery中的元素属性 - Loop through array, assign each value to an element attribute in Javascript / Jquery 循环遍历每个数组的每个项目,但仅遍历第一个数组的长度 - loop that goes through every item of every array but only for the first array's length 如何在不执行 [0] 的情况下循环遍历数组键 - How to loop through array keys without doing [0] 如何遍历对象数组并使用lodash检查该对象中的值是否与另一个数组中的项匹配 - how to loop through array of objects and check if a value in that object matches an item in another array using lodash 如何遍历数组以将HTML分配给工具提示 - How can I Loop through array to assign html to tooltip 在JavaScript中,当通过FOR循环循环时,如何将数组中该项的值传递给匿名函数? - In JavaScript, when looping through a FOR loop, how do I pass the value of the item in an array to an anonymous function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM