如何将一个对象扩展到AB对象,而不会在我向AB对象插入另一个值时影响一个对象?

时间:2017-01-19 14:22:35

标签: javascript jquery

以下是我的简化案例:



var a = {
	filters: ["aa"]
}
var b = {
	filters:["bb","bbb"]
}
var ab = {
}

$.extend(ab, a);
console.log(JSON.stringify(a)); //{"filters":["aa"]}
console.log(JSON.stringify(ab)); //{"filters":["aa"]}

for (var i = 0; i < b.filters.length; i++){
	ab.filters.push(b.filters[i]); //it only inserts to 'ab', but why 'a' also has it?
}

console.log(JSON.stringify(a)); //{"filters":["aa","bb","bbb"]} -> it should be only "aa", shouldn't it??
console.log(JSON.stringify(ab)); //{"filters":["aa","bb","bbb"]}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

如您所见,我将a对象扩展为ab对象。然后,我将b对象的值插入ab对象。不知何故,a对象还具有b对象的值。

是否有任何解决方案可以阻止b对象将其值插入a对象?

3 个答案:

答案 0 :(得分:2)

您需要将true作为$.extend的第一个参数传递原始对象的深层副本:

var a = { filters: ["aa"] }
var b = { filters: ["bb", "bbb"] }
var ab = {}

$.extend(true, ab, a); // < note true here
console.log(JSON.stringify(a)); // {"filters":["aa"]}
console.log(JSON.stringify(ab)); // {"filters":["aa"]}

for (var i = 0; i < b.filters.length; i++) {
  ab.filters.push(b.filters[i]);
}

console.log(JSON.stringify(a)); // {"filters":["aa"]}
console.log(JSON.stringify(ab)); // {"filters":["aa","bb","bbb"]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

答案 1 :(得分:0)

true作为extend函数的第一个参数传递给深层复制对象。

$.extend(true, ab, a);

appears the thunk is able to be specialised

答案 2 :(得分:0)

只是做:

$.extend(ab, JSON.parse(JSON.stringify(a)));

选中此fiddle