As a newcomer to the world of JS, I hope you can bear with me if my question seems complex and possibly repetitive. This issue has been bothering me for quite some time now without finding a satisfactory answer or solution.
I have an array of Objects where I intend to modify certain properties based on another array of equal length. Initially, I assumed this could be easily achieved using a simple for-loop, but to my surprise, all properties ended up with the same value.
Below is the original array of Objects (dattmp
) along with the accompanying array (color
):
var testdat = {
Element1: {time: [1586777601886.39, 1586777608597.8, 1586777615309.21]},
Element2: {time: [1586777603886.39, 1586777638597.8, 1586777315309.21]}
}
var options = {pathOptions: {className: "myclass"}}
var dattmp = [];
for (kys in testdat) {
var tmp = {
type: "Feature",
properties: {
time: testdat[kys].time,
path_options: options.pathOptions
}
};
dattmp.push(tmp);
}
var color = ["orange", "blue"];
My objective is to assign distinct colors to each Object within dattmp
, such that the first item is orange and the second one is blue.
I attempted both a conventional for-loop
and a map
, but surprisingly, both instances resulted in all objects having the color blue
.
for (var i = 0; i < color.length; i++) {
dattmp[i].properties.path_options.color = color[i];
}
const newdat = dattmp.map((dt, i) => {
dt.properties.path_options.color = color[i];
return dt;
});
The following method appears to yield the desired outcome, although my IDE indicates numerous issues with the code. Moreover, I am unsure about the usage of the ...
notation. Hence, my query is: What would be the correct approach for modifying values individually?
const newdat1 = dattmp.map((dt, i) => {
dt = { ...dt, properties: {...dt.properties, path_options: {...dt.properties.path_options, color: color[i]}}};
return dt;
});