Vlad
Vlad

Reputation: 511

How to loop through array and assign every item a value without loop?

I have an array of object like so:

let data = [{Date : null, id: null}, {Date : null, id: null}, {Date : null, id: null}]

And i need to assign every Date property a value. 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. Is it possible to use i as index iterator in map ?

Upvotes: 0

Views: 59

Answers (2)

Hangover Sound Sound
Hangover Sound Sound

Reputation: 192

You can do it more functional, in a cleaner way by using 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);

Upvotes: 1

0stone0
0stone0

Reputation: 44083

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

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);

Upvotes: 2

Related Questions