简体   繁体   中英

Using delete property without affecting parent object

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 ?

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> 

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));

你应该试试 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM