我正面临下一个问题,我可以合并/扩展对象并且工作得很好,但是现在我需要做一个扩展对象的反义,JQuery doc:
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
// Result
{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}
哪个很酷,而且效果很好,但是如何进行相反的操作,例如获得这样的输出:
{"apple":0,"banana":{"weight":52},"cherry":97}
答案 0 :(得分:8)
没有这样的功能,但你可以写自己的:
$.prototype.reduce = function reduce(obj1, obj2) {
for (var k in obj2) {
if (obj1.hasOwnProperty(k) && obj2.hasOwnProperty(k)) {
if (typeof obj1[k] == "object" && typeof obj2[k] == "object") {
reduce(obj1[k], obj2[k]);
}
else delete obj1[k];
}
}
}
答案 1 :(得分:1)
在JavaScript中,您可以使用delete
运算符完全从对象中删除属性:
var foo = {
bar: "This is bar"
};
snippet.log(foo.bar); // "This is bar"
snippet.log(foo.hasOwnProperty('bar')); // true
delete foo.bar;
snippet.log(foo.hasOwnProperty('bar')); // false

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
因此,要修改您的对象,只需删除您不想要的属性。
旁注:99.99%的时间并不重要,但请注意,从对象中删除属性会使某些JavaScript引擎无法优化,并且会映射到#34;映射&#34;对象的版本而不是优化的对象,这意味着访问对象上的其余属性要慢得多。同样,它很重要,但它确实适用于非常罕见的时间。
答案 2 :(得分:1)
我也遇到过这样的问题。我必须实现递归reduce操作:
$.reduce({a: 1, b: 2}, {b: 12, e: 13}) => {a: 1, b: 12}
以下是我的表现
$.reduce = function reduce(templateObj, toReduce, modifyCopy, doNotAppend) {
if (!toReduce) {
return toReduce;
}
if (!templateObj) {
return toReduce;
}
// not changing the src toReduce
var toModify = modifyCopy
? $.extend(true, {}, toReduce)
: toReduce;
// will append missing properties from templateObj
var merged = doNotAppend
? toModify
: $.extend(true, {}, templateObj, toModify);
// go through all the properties in toReduce or (templateObj + toReduce)
$.each(merged, function (propName, value) {
if (!(propName in templateObj)) {
delete toModify[propName];
return;
}
if (!(propName in toModify)) {
toModify[propName] = templateObj[propName];
return;
}
if (typeof templateObj[propName] == "object" && typeof toModify[propName] == "object") {
toModify[propName] = $.reduce(templateObj[propName], toModify[propName]);
}
});
return toModify;
}