我想知道如何通过在javascript中传递值数组来过滤对象
如何将值数组作为参数传递并使用javascript过滤对象。
基于send
和receive
与id
,在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
}
]
答案 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);