2 回答
TA贡献1815条经验 获得超13个赞
您可以使用Array.map()、解构对象并使用别名创建具有新名称的变量,然后您可以使用速记属性名称重建对象:
const items = [{"A":"Q1234","B":"W1234","C":19.9,"D":2},{"A":"Q1234","B":"W1234","C":19.9,"D":2}]
const result = items.map(({ A: id, B: power, C: health, D: mana }) => ({
id,
power,
health,
mana
}))
console.log(result)
TA贡献1796条经验 获得超4个赞
一旦输入被固定以便可以解析JSON,创建一个函数,其将所述A,B,C,D的对象的键入id,power等的键,并.map在该功能中的每个对象:
const responseText = `{ "items": [
{
"A": "Q1234",
"B": "W1234",
"C": 19.9,
"D": 2
},
{
"A": "Q1234",
"B": "W1234",
"C": 19.9,
"D": 2
}]}`;
const input = JSON.parse(responseText);
const keyMap = {
A: 'id',
B: 'power',
C: 'health',
D: 'mana'
};
const transform = shortObj => Object.fromEntries(
Object.entries(shortObj).map(([key, val]) => [keyMap[key], val])
);
console.log(input.items.map(transform));
添加回答
举报