skip to Main Content

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

https://jsfiddle.net/51fx6gsj/4/

2

Answers


  1. Chosen as BEST ANSWER

    Ok my fault, ... later in code i've a Eventemitter

    this.appService.pendingEmitter.emit({
          pending: true,
          devices: _devices,
        });
    

    This part has change the apiProp back to Original


  2. The code has two interesting features:

    1. The await Promise.all( mappedArray) achieves little because all the entries of the mapped array are undefined and there is no asynchronous code inside the function passed to .map. Unless there are bigger plans afoot, the await Promise.all wrapper) can probably be removed and the devices.map statement replaced with devices.forEach.

    2. In the jsFiddle, editProp calls saveProp 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 to saveProp.

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search