为了账号安全,请及时绑定邮箱和手机立即绑定

在Javascript中合并JSON和对象

在Javascript中合并JSON和对象

慕婉清6462132 2022-05-26 11:22:03
我有以下 json 和对象。acctData = [{"acctNum": "AAA - 1234","user": "Alice"},{"acctNum": "AAA - 5231","user": "Bob"},{"acctNum": "AAA - 9921","user": "Alice"},{"acctNum": "AAA - 8191","user": "Alice"}];balance = {"AAA - 1234": 4593.22,"AAA - 9921": 0,"AAA - 5231": 232142.5,"AAA - 8191": 4344};我想合并它以获得以下响应[{acctNum: "AAA - 1234", user: "Alice", balance: 4593.22},{acctNum: "AAA - 5231", user: "Bob", balance: 232142.5},{acctNum: "AAA - 9921", user: "Alice", balance: 0},{acctNum: "AAA - 8191", user: "Alice", balance: 4344}]function myFunction() {    for (var key in acctData) {       for(var name in balance) {         if ( acctData[key].acctNum === name) {          acctData[key]['balance']= balance[acctData[key].acctNum];          break;         }       }     }}我这是使用香草javascript的正确方法还是有更有效的方法?
查看完整描述

2 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

您只需使用地图即可。


const acctData = [

  {

  "acctNum": "AAA - 1234",

  "user": "Alice"

  },

  {

  "acctNum": "AAA - 5231",

  "user": "Bob"

  },

  {

  "acctNum": "AAA - 9921",

  "user": "Alice"

  },

  {

  "acctNum": "AAA - 8191",

  "user": "Alice"

  }

];


const balance = {

  "AAA - 1234": 4593.22,

  "AAA - 9921": 0,

  "AAA - 5231": 232142.5,

  "AAA - 8191": 4344

};


const newAccount = acctData.map(acc => {

  acc.balance = balance[acc.acctNum];

  return acc;

});


console.log(newAccount);


查看完整回答
反对 回复 2022-05-26
?
噜噜哒

TA贡献1784条经验 获得超7个赞

您可以使用.map()和对象解构:


let result = acctData.map(({acctNum, user}) => ({acctNum, user, balance: balance[acctNum]}));

let acctData = [

{

"acctNum": "AAA - 1234",

"user": "Alice"

},

{

"acctNum": "AAA - 5231",

"user": "Bob"

},

{

"acctNum": "AAA - 9921",

"user": "Alice"

},

{

"acctNum": "AAA - 8191",

"user": "Alice"

}

];

let balance = {

"AAA - 1234": 4593.22,

"AAA - 9921": 0,

"AAA - 5231": 232142.5,

"AAA - 8191": 4344

};


let result = acctData.map(({acctNum, user}) => ({acctNum, user, balance: balance[acctNum]}));


console.log(result);


查看完整回答
反对 回复 2022-05-26
  • 2 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信