0

I have an array data, that contains a nodeData object, which contains an id

I make 2 copies of the array:

    const dropAboveData = data.slice();
    const dropBelowData = data.slice();

and then I try to modify both copies of my 2 copied arrays differently

    for(let i = 0; i<data.length; i++){
        dropAboveData[i].nodeData.id = -1;
        dropBelowData[i].nodeData.id = -2;
    }

So for example if each record in data had data[i].nodeData.id = 0, at the end i would expect dropAboveData to contain all -1 for id, and dropBelowData to contain all -2 for id.

But instead it seems like data, dropAboveData, and dropBelowData all become arrays filled with -2.

Why is this happening? I though slice() makes a copy of the array so that i'm not accessing the same object?

2
  • 4
    slice makes array copy but not copy of objects in the array Commented Jul 21, 2018 at 17:29
  • Whats inside data ? Commented Jul 21, 2018 at 17:32

2 Answers 2

1

Slice makes a shallow copy

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

You could copy an array of objects like this:

var data = [{
  'a': '0'
}, {
  'b': '1'
}, {
  'c': '2'
}]
dropAboveData = []
dropBelowData = []

data.map(o => {
  dropAboveData.push(JSON.parse(JSON.stringify(o)));
  dropBelowData.push(JSON.parse(JSON.stringify(o)));
});

dropAboveData[0] = 1; //<-- modify only dropAboveData
dropAboveData[1].b = 99;//<-- modify only dropAboveData

console.log(dropAboveData)
console.log(dropBelowData)

Sign up to request clarification or add additional context in comments.

Comments

0

as charieftl pointed out i was not copying the objects in my array (nodeData objects).

    const dropAboveData = data.map(item => item.nodeData.id = -1);
    const dropBelowData = data.map(item => item.nodeData.id = -2);

did what I wanted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.