说我有两个对象,如下所示。
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]}
答案 0 :(得分:3)
只需使用for loop
和delete
:
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]