在Javascript中合并JSON和对象

我有以下 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的正确方法还是有更有效的方法?


慕婉清6462132
浏览 88回答 2
2回答

心有法竹

您只需使用地图即可。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);

噜噜哒

您可以使用.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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript