0

I want to clone my array of objects. Every one tells to use slice(0) but i don't understand, it's not working, check the fiddle. The property is avalaible in the two arrays.

I want to edit my objects in the first array and not in my second too. I already checked : How to clone a Javascript Array of Objects? It's the same with concat, extend. The only one i found is JSON.parse. I want to understand why people say the method slice cloned arrays.

var arr = [{'obj1':1}, {'obj2':2}];
var clone = arr.slice(0);
clone[0].test = "defined";

https://jsfiddle.net/zkzv2mp0/2/

8
  • 2
    What you want is a deep clone, not a shallow clone. Commented Jul 13, 2017 at 13:02
  • Because JSON.stringify serializes everything into text form and JSON.parse makes objects out of that. No reference is kept. slice(0) is, as the answer already says, a shallow cloning method. I’m not exactly sure, where the misunderstanding is. Commented Jul 13, 2017 at 13:03
  • stackoverflow.com/questions/122102/… Reference this question for deep cloning Commented Jul 13, 2017 at 13:04
  • It does clone array check arr === clone // false. But it doesn't clone elements arr[0] === clone[0] //true Commented Jul 13, 2017 at 13:05
  • Ok, just understood, thanks. I will use var clone = JSON.parse(JSON.stringify(arr)); Commented Jul 13, 2017 at 13:05

3 Answers 3

0

The fiddler is pure JS. does not havejquery included.

See working example:

https://jsfiddle.net/zkzv2mp0/3/

But as you can see using slice(0); is a Shallow clone, where you want to update one without updating the original (deep clone) JSON.parse(JSON.stringify(arr))

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

Comments

0
var clone = JSON.parse(JSON.stringify(arr));

You could use JSON Stringify and JSON Parse to clone an Array. But be careful this only works if your array contains JSON serializable content.

Comments

0

Ain't cristal clear what you want to do...

But here is what I think you try to achieve:

// Your initial array of objects.
var arr = [{'obj1':1}, {'obj2':2}];

// A cloned array of objects.
var clone = jQuery.extend(true, [], arr);

// Now sliced, keep the first object only
clone = clone.slice(0,1);
console.log(clone);

// Change the value of the object.
clone[0].obj1 = "defined";
console.log(clone);

// Show them in page.
$("#testarr").html(arr[0].obj1);
$("#testclone").html(clone[0].obj1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
In arr :
<span id="testarr">
</span></p>
<p>
In clone :
<span id="testclone">
</span>
</p>

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.