使用delete属性而不影响父对象

时间:2015-11-25 11:05:42

标签: javascript

以下是两个名为primarysecondary对象

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

当我使用delete secondary['lol'];时,它会从两个对象中删除该属性:jsfiddle

我的问题是:如何从secondary删除属性而不将其从primary删除?

3 个答案:

答案 0 :(得分:4)

secondary引用与primary相同的对象。如果要将它们分开,则需要创建primary的副本。

有像Lodash这样的库,它们具有允许您克隆对象的实用程序功能(下面的示例),但是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>

答案 1 :(得分:2)

创建小提琴意味着创建工作小提琴,而不仅仅是粘贴代码

http://jsfiddle.net/Lso7kwLs/

克隆对象可以帮到你。例如:

$D$9

答案 2 :(得分:1)

你应该尝试:

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