Home > Mobile >  How can I assign array values into object keys for other object?
How can I assign array values into object keys for other object?

Time:10-12

So I have an array of objects [{}, {}, {}] and simple array [true, false, true]

Is there any way to make first array [{value: true}, {value: false}, {value: true}]?

CodePudding user response:

Assuming your array of objects is called objects and your simple array is called array, then you can execute:

objects.forEach((o, i) => o['value'] = array[i])

CodePudding user response:

You can map each element of the array to the object:

console.log([true, false, true].map(el => ({ value: el })));

or if you want to overwrite the elements in the first array

const arr = [{}, {}, {}];
const arr2 = [true, false, true];
arr.forEach((el, idx) => el.value = arr2[idx]);

console.log(arr);

  • Related