javascript - javascript: 重命名API对象的键

我从API中得到了以下数据数组。


[


 {


"barCode":"31568308949"


"itemDesc":"ASHTON-250"


"permPrice": 19.99


 }


]



预期结果如下所示。


[


 {


"Bar Code":"31568308949"


"Item Description":"ASHTON-250"


"Prem Price": 19.99


 }


]



谁能帮我实现这个目标。 先谢谢了。

时间:

如果它总是这三个字段,那么只需显式重命名即可。


let input = [{'barCode': '31568308949', 'itemDesc': 'ASHTON-250', 'permPrice': 19.99}];



let output = input.map(x => ({


 'Bar Code': x.barCode,


 'Item Description': x.itemDesc,


 'Prem Price': x.permPrice,


}));



console.log(output);

另一种解决方案是创建 keyMap,你可以在其中添加新密钥,它将动态映射你添加的任何新密钥:


let keyMap = {


 barCode:"Bar Code",


 itemDesc:"Item Description",


 permPrice:"Prem Price"


};



let input = [{"barCode":"31568308949","itemDesc":"ASHTON-250","permPrice": 19.99 }];



let newData = input.map(obj => {


 return Object.keys(obj).reduce((prev, next) => {


 if (next in keyMap) {


 prev[keyMap[next]] = obj[next];


 } else {


 prev[next] = obj[next];


 }



 return prev;


 }, {});


});



console.log(newData);

你可以使用映射函数和 delete 运算符来实现这里要求。


var a = [ {"barCode":"31568308949","itemDesc":"ASHTON-250","permPrice": 19.99 } ];



var c = a.map(b=> {



b["Bar Code"] = b.barCode;


b["Item Description"] = b.itemDesc;


b["Prem Price"] = b.permPrice; 


delete b.barCode;


delete b.itemDesc;


delete b.permPrice;


return b;



})


console.log(c)




var a = [ {"barCode":"31568308949","itemDesc":"ASHTON-250","permPrice": 19.99 } ];



var c = a.map(b=> {



b["Bar Code"] = b.barCode;


b["Item Description"] = b.itemDesc;


b["Prem Price"] = b.permPrice; 


delete b.barCode;


delete b.itemDesc;


delete b.permPrice;


return b;



})



console.log(c)
...