I’ve encountered a strange behavior in my JavaScript code that I can’t seem to explain. I have an array of objects (devices), and I deep copy it (_devices) before manipulation. Then, I assign a value to each object in devices, but the values appear to be identical after logging, even though they should be different.
const _devices = JSON.parse(JSON.stringify(devices)); // Deep copy
await Promise.all(
devices.map((dev, idx) => {
dev.apiProp = data[idx];
dev.pending = true;
_devices[idx].pending = true;
})
);
console.log(_devices[0].apiProp, devices[0].apiProp); // Different values in apiProp >>> CORRECT!
console.log(_devices[0], devices[0]); // Identical values for apiProp, though they should be
different
here is a minimal example in JSFiddle
2
Answers
Ok my fault, ... later in code i've a Eventemitter
This part has change the apiProp back to Original
The code has two interesting features:
The
await Promise.all( mappedArray)
achieves little because all the entries of the mapped array areundefined
and there is no asynchronous code inside the function passed to.map
. Unless there are bigger plans afoot, theawait Promise.all
wrapper) can probably be removed and thedevices.map
statement replaced withdevices.forEach
.In the jsFiddle,
editProp
callssaveProp
with a prop object as second argument. However,saveProp
is expecting an array of prop objects, and will get undefined when trying to retrieve data entries using a numeric index. The likely remedy would be to pass a suitable array tosaveProp
.I strongly suspect the 2nd error is the actual cause of the unexpected output.
PS. I’ve just seen your post and the later emitter may be the actual reason, but please consider the two issues noted above.