简体   繁体   中英

Pass array of values and filtering object in javascript

I would like to know how to filter object by passing arrays of values in javascript

How to pass array of values as arguments and filter the object using javascript. Based on send and receive with id , get the object value in javascript.

for id trans, if send (in) is bank and receive (out) is bank , for id fund, if send (in) is credit and receive (out) is bank and for id insta, if send (in) is debit and receive (out) is bank , get result obj

var send=['bank', 'credit', 'debit'];
var receive = ['bank', 'bank', 'bank'];
var id=['trans', 'fund', 'insta'];
var result = getSample(sample,send, receive, id);


I have tried but got stuck
function getSample(sample,sn, rcn, id){
  const temp = sample.map(e => Object.entries(e).map(([k, val]) => val)).flat(3)
    var selectval= temp.filter(x=>x.in==scn && x.out==rcn && x.id == id);
   return selectval;
}

var sample =
  [{
    "btob": [{
      "id": "trans",
      "in": "bank",
      "out": "bank",
      "value": 10,
    },{
      "id": "fund",
      "in": "bank",
      "out": "bank",
      "value": 10
    },{
      "id": "insta",
      "in": "bank",
      "out": "bank",
      "value": 10
    }],
    "ctob": [{
      "id": "trans",
      "in": "credit",
      "out": "bank",
      "value": 20
    },{
      "id": "fund",
      "in": "credit",
      "out": "bank",
      "value": 10
    },{
      "id": "insta",
      "in": "bank",
      "out": "bank",
      "value": 10
    }],
   "dtob": [{
      "id": "trans",
      "in": "debit",
      "out": "bank",
      "value": 20
    },{
      "id": "fund",
      "in": "debit",
      "out": "bank",
      "value": 10
    },{
      "id": "insta",
      "in": "debit",
      "out": "bank",
      "value": 10
    }]
}]

Expected Output:
  result=[
    {
      "id": "trans",
      "in": "bank",
      "out": "bank",
      "value": 10,
    },
    {
      "id": "fund",
      "in": "credit",
      "out": "bank",
      "value": 10
    },
    {
      "id": "insta",
      "in": "debit",
      "out": "bank",
      "value": 10
    }
  ]



Just declare arrays id,send,receive and sample, Then run the below code.

const temp = sample.map(e => Object.entries(e).map(([k, val]) => val)).flat(3);
var jointArray = id.map((currentValue, index) => {
  return id[index]+"-"+send[index]+"-"+receive[index];
});
var result = temp.filter(function(item) { 
   return ( jointArray.indexOf(item.id+"-"+item.in+"-"+item.out)!=-1  ) 
});
console.log(result);  

here is js fiddle https://jsfiddle.net/qcxntpfy/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM