如何根据javascript中的条件更新特定对象
根据条件,我有一个名为obj的对象:
'in'=="credit"
,'out'=="bank"
和"id"=="trans"
,获取对象,并将默认值添加为'in'=="bank"
,'out'=="bank"
和"id"=="fund
。
'in'=="debit"
,'out'=="bank"
和"id"=="fund"
,获取对象,并将默认值添加为'in'=="bank"
,'out'=="bank"
和"id"=="trans"
。
我尝试过滤器但卡住了
function getValue(send,receive, id){
const temp = obj.map(e => Object.entries(e).map(([k, val]) => val)).flat(3)
this.selectedProviderList = temp.filter(x=>x.in== send && x.in ==receive && x.id==id);
}
getValue("credit", "bank", "trans");
var obj = [{
"btob": [{
"id": "trans",
"in": "bank",
"out": "bank",
"value": 10
},{
"id": "fund",
"in": "bank",
"out": "bank",
"value": 10
}],
"ctob": [{
"id": "trans",
"in": "credit",
"out": "bank",
"value": 20
},{
"id": "fund",
"in": "credit",
"out": "bank",
"value": 10
}],
"dtob": [{
"id": "trans",
"in": "debit",
"out": "bank",
"value": 20
},{
"id": "fund",
"in": "debit",
"out": "bank",
"value": 10
}]
}]
// get the values if 'in' is 'credit' and 'out' is 'bank' and id is "trans"
Expected Output
[
{
"id": "trans",
"in": "credit",
"out": "bank",
"value": 20
},
{
"id": "fund",
"in": "bank",
"out": "bank",
"value": 10
}
]
// get the values if 'in' is 'debit' and 'out' is 'bank' and id is "fund"
[{
"id": "fund",
"in": "debit",
"out": "bank",
"value": 10
},{
"id": "trans",
"in": "bank",
"out": "bank",
"value": 10
}]
答案 0 :(得分:1)
由于in
是JavaScript中的保留关键字,因此您需要使用[]
(方括号)表示法。 (我还将第二个in
更改为out
)。
function getValue(send, receive, id) {
const temp = obj.map(e => Object.entries(e).map(([, val]) => val)).flat(3);
this.selectedProviderList = temp.filter(x => x["in"] == send && x["out"] == receive && x["id"] == id);
}
getValue("credit", "bank", "trans");