I am attempting to match an array being passed through as arguments to a Javascript class method to an array of objects that are also being created within the method.
For example, here's an array being passed:
colorSet = ["red","orange","purple","yellow"]
When this array is passed in the below method called addColors, I need to create an object and push the object to an empty array based on the length of the colorSet. This is simple enough.
addColors(colorSet) {
let obj = {}
for (let i = 0;i<colorSet.length;i++){
this.legend.push(obj)
}
However, after doing this, I attempted within the same for loop to add object key 'color' to the array of objects and set its value to the array of colors in colorSet. See below:
addColors(colorSet) {
let obj = {}
for (let i = 0;i<colorSet.length;i++){
this.legend.push(obj)
this.legend[i].color = colorSet[i]
}
However, here is the result:
0: Object { color: "yellow" }
1: Object { color: "yellow" }
2: Object { color: "yellow" }
3: Object { color: "yellow" }
What I want is this:
0: Object { color: "red" }
1: Object { color: "orange" }
2: Object { color: "purple" }
3: Object { color: "yellow" }
Any help on this would be greatly appreciated.