我想我已经看过这样一个jquery函数,但找不到它。
var x = {a:1, b:2};
var y = {a:5, c:3};
var z = $.extend({}, x, y); // {a: 5, b: 2, c: 3}
// want a similar jquery function which returns {a: 5, b: 2}
// that is, returns only attributes which x has (a,b), but adds no new attributes (c)
答案 0 :(得分:0)
在这里编写自己的方法可能会更容易。
浏览Y的所有道具并覆盖X
for (var yItem in Y) {
if (X.hasOwnProperty(yItem)) {
X[yItem] = Y[yItem];
}
}
var X = {a:1, b:2};
var Y = {a:5, c:3};
for (var yItem in Y) {
if (X.hasOwnProperty(yItem)) {
X[yItem] = Y[yItem];
}
}
alert(JSON.stringify(X));

答案 1 :(得分:0)
只需使用Object.assign()
和Object.defineProperty
分享另一种解决方案。
var x = {a:1, b:2 };
var y = {a:5, c:3, d:5};
Object.leftJoin = function(leftObj, rightObj) {
var acceptKeyList = Object.keys(leftObj);
var returnObj = {};
for(var key of Object.keys(rightObj)) {
if(acceptKeyList.indexOf(key) < 0) {
Object.defineProperty(rightObj, key, {
enumerable: false
});
}
}
return Object.assign(returnObj, leftObj, rightObj);
}
console.log(Object.leftJoin(x, y));