0

Original array is newData. I wanted add one more array element to newData and added array Element should have Rank 1.

Issue is Rank is getting updated to 1 for both the records. Rank should be 1 for second record and 1st record should be null

Please tell me what i'm doing wrong here.

let newData = [{
    "key1": {
        "cc":'IND'   
    },          
    "key2": {
        "rank": null
    }
}];

let setData = newData.concat(newData.slice());

setData.forEach(data => { 
    data.key2.rank =+ 1;
});
Pankaj Bisht
  • 986
  • 1
  • 8
  • 27
Arun K
  • 73
  • 6
  • Possible duplicate of [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – ASDFGerte May 23 '18 at 09:51

2 Answers2

1

You can try following

let newData = [{"key1": {"cc":'IND' }, "key2": {"rank": null}}];

    // Concatenate arrays use spread operator and can use map rather than slice
    let setData = [...newData, ...newData.map(data => { 
        /* Objects are passed by reference, you need to break the reference
         * to create the clone of the object. */
        data = JSON.parse(JSON.stringify(data));
        data.key2.rank =+ 1; 
        return data;
    })];

console.log(setData);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0
setData.forEach(data => { 
  data.key2.rank += 1;
});

Try to flip your operator from =+ to += instead

Isaac
  • 12,042
  • 16
  • 52
  • 116