我想知道如何使用javascript过滤出嵌套数组中的对象。
我有obj sample_obj
,其中有不同的键,我想使用javascript中的payin ==“ bank” && payout ==“ bank”进行过滤。
var result= sample_obj.filter((e)=>{
e.payin=="bank" && e.payout=="bank"
})
console.log("Result:", result);
//inputs
var sample_obj = [{
obj1: [{
id: "IN",
amount: 100,
payin: "bank",
payout: "bank"
},{
id: "IN",
amount: 200,
payin: "credit",
payout: "bank"
}],
obj2: [{
id: "TR",
amount: 120,
payin: "bank",
payout: "bank"
},{
id: "TR",
amount: 250,
payin: "debit",
payout: "bank"
}]
}]
Output:
Result:[{
id: "IN",
amount: 100,
payin: "bank",
payout: "bank"
}, {id: "TR",
amount: 120,
payin: "bank",
payout: "bank"}]
答案 0 :(得分:0)
由于具有函数主体{}
,因此需要使用return
。由于您的数据结构,您还需要更改一些内容:
var sample_obj = [{
obj1: [{
id: "IN",
amount: 100,
payin: "bank",
payout: "bank"
},{
id: "IN",
amount: 200,
payin: "credit",
payout: "bank"
}],
obj2: [{
id: "TR",
amount: 120,
payin: "bank",
payout: "bank"
},{
id: "TR",
amount: 250,
payin: "debit",
payout: "bank"
}]
}]
var result= Object.values(sample_obj[0]).
reduce((acc, curr) => acc.concat(curr)).filter((e)=>{
return e.payin=="bank" && e.payout=="bank"
});
console.log("Result:", result);