在javascript中传递值数组和过滤对象

时间:2019-04-08 06:55:27

标签: javascript jquery arrays object

我想知道如何通过在javascript中传递值数组来过滤对象

如何将值数组作为参数传递并使用javascript过滤对象。 基于sendreceiveid,在javascript中获取对象值。

对于id而言,如果send(输入)为bank,而receive(输出)为bank, 对于id基金,如果send(输入)为credit,而receive(输出)为bank,并且 对于id insta,如果send(in)为debit,而receive(out)为bank,则得到结果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
    }
  ]



1 个答案:

答案 0 :(得分:0)

只需声明数组ID,发送,接收和采样,然后运行以下代码即可。

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);  

这是js小提琴https://jsfiddle.net/qcxntpfy/