Home > Net >  Assign array of values to attributes in an array of objects
Assign array of values to attributes in an array of objects

Time:07-25

Suppose I have an array with JSON objects. To simplify, the objects look like this:

var object = {
attribute1: ""
};

All of them contain attribute1.

Then, I have an array with the values that I want to pass to the attribute in these objects (as many values as objects in the array):

var values1 = ["a", "b", "c"];

My question is: How can I take these values and assign them to the elements in the array so that in the end I get:

array[0].attribute1 is "a", array[1].attribute1 is "b", and array[2].attribute1 is "c".

Please, can this be done in plain javascript (no JQuery)? Am I supposed to just create a for loop and iterate across all objects in the array?

CodePudding user response:

There's no way to do it without some kind of loop -- there's nothing built-in that merges arrays like this.

Loop over array and assign the attribute from the corresponding index in values1.

var object = {
  attribute1: "",
  attribute2: ""
};
var array = [JSON.parse(JSON.stringify(object)), JSON.parse(JSON.stringify(object)), JSON.parse(JSON.stringify(object))];
var = ['a', 'b', 'c'];

array.forEach((obj, index) => obj.attribute1 = values1[index]);

console.log(array);

  • Related