0

I would like to know how to filter out object in a nested array using javascript. I have obj sample_obj in which has different keys, I want to filter using payin=="bank" && payout=="bank" in javascript.

   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"}]

Senthil
  • 961
  • 1
  • 8
  • 21
  • You need to `return` inside filter `return e.payin=="bank" && e.payout=="bank"` OR remove the `{}` wrapper for implicit return – adiga May 24 '19 at 08:36
  • @adiga thanks for reply, It doesnot work , but my question is since i have two different keys, `obj1` and `obj2` inside `sample_obj`, how to use filter – Senthil May 24 '19 at 08:42
  • I have voted to reopen the question since `return` is not the only issue with your question. You have a nested arrays inside an object. You need to loop through each property and do the filtering – adiga May 24 '19 at 08:57

1 Answers1

0

Because you have the function body {}, you need to use return. You also need to change a few things due to your data structure:

 

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);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79