热更新javascript中的特定对象

时间:2019-04-05 07:58:40

标签: javascript jquery arrays json object

如何根据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
    }]

1 个答案:

答案 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");