根据其他对象删除对象的键

时间:2017-12-29 13:56:51

标签: javascript

我需要一种方法来自动删除对象的键以使其具有相同的键。

示例:

var objA = {key1:1, key2:2, key3:3};
var objB = {key1:4, key2:5, key3:6, key4:7, key5:8}

在这种情况下,我希望我的objB仅保留key1key2key3,因为这些是在这两个对象之间共享的。

6 个答案:

答案 0 :(得分:1)

您可以使用此代码来实现您的目标。



var objA = {key1:1, key2:2, key3:3};
var objB = {key1:4, key2:5, key3:6, key4:7, key5:8};
Object.keys(objB).forEach(function(key){
   if(!objA[key]){
     delete objB[key];
   }
});
console.log(objB);




答案 1 :(得分:1)

使用for..in循环对象hasOwnProperty以检查对象是否具有属性,delete是否删除密钥



var objA = {
  key1: 1,
  key2: 2,
  key3: 3
};
var objB = {
  key1: 4,
  key2: 5,
  key3: 6,
  key4: 7,
  key5: 8
}

for (var keys in objB) {
  if (!objA.hasOwnProperty(keys)) {
    delete objB[keys]
  }
}
console.log(objB)




答案 2 :(得分:1)

您可以使用Array.filterArray.reducevar objA = {key1:1, key2:2, key3:3}; var objB = {key1:4, key2:5, key3:6, key4:7, key5:8} console.log(Object.keys(objB) .filter(key => objA[key]) .reduce((obj, key) => { obj[key] = objB[key]; return obj; }, {}));来实现此目标:



.includes()




答案 3 :(得分:1)

如果您不介意创建新对象来替换旧对象,则可以对.reduce()的结果使用Object.entries(),如下所示:



var objA = {key1:1, key2:2, key3:3};
var objB = {key1:4, key2:5, key3:6, key4:7, key5:8};

objB = Object.entries(objB).reduce((res, [k,v]) =>
  k in objA ? Object.assign(res, {[k]:v}) : res
, {});

console.log(objB);




或者使用for-of循环来使用它,你可以这样做:



var objA = {key1:1, key2:2, key3:3};
var objB = {key1:4, key2:5, key3:6, key4:7, key5:8};

var res = {};
for (const [k,v] of Object.entries(objB)) {
  if (k in objA) res[k] = v;
}

console.log(res);




答案 4 :(得分:1)

var objA = { key1: 1, key2: 2, key3: 3 };
var objB = { key1: 4, key2: 5, key3: 6, key4: 7, key5: 8 };

objB = Object.keys(objB).reduce(function(result, key) {
  if (objA.hasOwnProperty(key)) {
    result[key] = objB[key]
  }

  return result;
}, {});

这是一个ES5版本,它不使用delete运算符,而是构造一个只有objA密钥的新对象,并将其分配给objB。< / p>

答案 5 :(得分:0)

尝试更现代的JavaScript:

&#13;
&#13;
function reduceObject(baseObject = {}, dataObject = {}) {
  return Object.keys(baseObject)
    .reduce((result, key) => {
      result[key] = dataObject[key];
      return result;
    }, {});
}
const objA = {key1:1, key2:2, key3:3};
const objB = {key1:4, key2:5, key3:6, key4:7, key5:8};

console.log(reduceObject(objA, objB));
console.log(reduceObject(objA));
console.log(reduceObject(undefined, objB));
console.log(reduceObject({ a: 'key' }, { a: 'thing', on: 'theFly' }));
&#13;
&#13;
&#13;