【问题标题】:hot to update particular object in javascript热门更新javascript中的特定对象
【发布时间】:2019-04-05 07:58:40
【问题描述】:

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

【问题讨论】:

  • 对不起,我不明白。对于预期的输出,数组中的第一个对象是由于过滤了inoutfund 值。但是数组中的第二个对象是从哪里来的呢?

标签: javascript jquery arrays json object


【解决方案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");

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多