0

Here are two objects named primary and secondary:

var primary = {"gonna":3,"lol":114,"wouldn":2,"know":6,"lowkey":2,"man":5};
var secondary = primary;

When I use delete secondary['lol']; it deletes the property from both objects: jsfiddle

My question is: how to delete a property from secondary without deleting it from primary?

neptune
  • 1,211
  • 2
  • 19
  • 32
  • 1
    You assign _reference_ of primary to variable secondary. It's still one object in memory. You need to clone primary to achieve desired behavior. – Tommi Nov 25 '15 at 11:08
  • This is most likely a duplicate. I'm sure this question has already been asked. – kemicofa ghost Nov 25 '15 at 11:09
  • The OP would have to know that the issue was caused by not copying the object first, before knowing to look at ways to clone an object. Also, it's an object here, not an array. – Merott Nov 25 '15 at 11:18
  • @LGSon You apparently don't know the difference between an object and an array, which can only confuse matters – Dexygen Nov 25 '15 at 11:25
  • @GeorgeJempty I do, retracted my vote, .. was a little too sleepy :), so thanks for wake me up – Asons Nov 25 '15 at 11:50

3 Answers3

5

secondary is referencing the same object as primary. You need to create a copy of primary if you want to keep them separate.

There are libraries like Lodash that have utility functions allowing you to clone an object (below example), but there are other ways too.

var primary = {"gonna":3,"lol":114,"wouldn":2,"know":6,"lowkey":2,"man":5};
var secondary = _.clone(primary);

delete secondary.lol;

document.write(JSON.stringify(primary));
document.write('<br>');
document.write(JSON.stringify(secondary));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
Community
  • 1
  • 1
Merott
  • 7,189
  • 6
  • 40
  • 52
3

Create fiddle mean create working fiddle, not just paste a code

http://jsfiddle.net/Lso7kwLs/

Cloning the object help you. For example:

var secondary = JSON.parse(JSON.stringify(primary));
James Ikubi
  • 2,552
  • 25
  • 18
z1m.in
  • 1,661
  • 13
  • 19
1

You should try :

var primary = {"gonna":3,"lol":114,"wouldn":2,"know":6,"lowkey":2,"man":5}; var secondary = $.extend({}, primary); delete secondary['lol'];

leena
  • 302
  • 3
  • 7