I'm quite new to JS, so excuse me if the question is overly complicated and probably a duplicate, but this problem bugged me for quite some time now and I couldn't find a satisfying answer or solution.
I have an array of Objects, where I want to change some properties based on another array of the same length. I thought this would be easily done in a for-loop, but to my surprise all properties end up having the same value.
Here is the array of Objects (dattmp) and the other 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 goal is to include the color in dattmp, so that the first Objects color is orange and the second one blue.
I tried a normal for-loop and a map but both color properties end up being 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 would work, but my IDE tells me there are a lot of problems with this code, and I don't really understand the ... notation. So my question is: What is the correct approach to changing the values individually?
const newdat1 = dattmp.map((dt, i) => {
dt = { ...dt, properties: {...dt.properties, path_options: {...dt.properties.path_options, color: color[i]}}};
return dt;
});