如何删除一个不在另一个对象中的对象的属性

时间:2019-06-15 16:32:21

标签: javascript object

说我有两个对象,如下所示。

let a = {Friday: [1, 2 3], Saturday: [2,4,2], Sunday: [1,4]}
let b = {Friday: [], Saturday: []}

我需要某种方式从a中删除不在b中的所有键值对,因此结果将是:

{Friday: [1, 2 3], Saturday: [2,4,2]}

4 个答案:

答案 0 :(得分:3)

只需使用for loopdelete

  • 遍历
  • 中的所有属性
  • 检查属性是否存在于b中,如果不存在,只需从a中删除该属性。

let a = {Friday: [1, 2, 3], Saturday: [2,4,2], Sunday: [1,4]};
let b = {Friday: [], Saturday: []};

for(let key in a){
  if(!(key in b))
    delete a[key];
}
console.log(a);

答案 1 :(得分:2)

  • 使用 public async sendTransaction(addressTo: string, amount: number) { const account; = this.web3.eth.accounts.privateKeyToAccount('0x' +this.privateKey); this.web3.eth.accounts.wallet.add(account); this.web3.eth.defaultAccount = account.address; const params = { //nonce: 0, to: addressTo, from: this.accountAddress, value: this.web3.utils.toWei(amount.toString(), 'ether'), gasPrice: 1, gasLimit: 21000, //chainId: 1 }; const transaction; =this.web3.eth.sendTransaction(params,function(err,transactionHash){ if (err) { console.log(err); } else { console.log(transactionHash) return transactionHash ; } }); console.log(transactionHash) return transaction.transactionHash; 获取b的密钥
  • 对此使用Object.keys来构建一个对象,其值将来自reduce()

a

如果您对一支衬纸感到困惑。下面是更容易理解的版本。

let a = {Friday: [1, 2, 3], Saturday: [2,4,2], Sunday: [1,4]};
let b = {Friday: [], Saturday: []}

let res = Object.keys(b).reduce((ac,k) => (ac[k] = a[k],ac),{});

console.log(res)

答案 2 :(得分:1)

您可以获取let res = Object.keys(b).reduce((ac,k) => { ac[k] = a[a]; return ac; },{}); 的所有键,从中删除a的键,并由此删除b的属性。

a

答案 3 :(得分:0)

最简单的方法是使用 for循环 if语句

// Removes the pairs from A that are not in B
for (let key in a) if (!b[key]) delete a[key]