gpt4 book ai didi

javascript - 如何将数组中的对象转换为特定格式

转载 作者:行者123 更新时间:2023-11-29 20:27:25 25 4
gpt4 key购买 nike

我有一个格式如下的 API:

[
{
"id": 4,
"code": "IN",
"name": "India",
"recordVersion": "6CB5C760-E145-4FFA-AC63-FAF5F36B6C80",
"updatedBy": "Sini "
},
{
"id": 59,
"code": "UK",
"name": "United Kingdom",
"recordVersion": "3512B084-8DB7-48F6-9E01-C0861E2A128D",
"updatedBy": "sinju "
}
]

我需要将它转换成这种格式:

localizedData = [ 
{
text: "India",
value: 4
},
{
text: "United Kingdom",
value: 59
}
];

我该怎么做?

最佳答案

假设您要将 name 属性映射到 text,并将 id 属性映射到 value

const source = [
{
"id": 4,
"code": "IN",
"name": "India",
"recordVersion": "6CB5C760-E145-4FFA-AC63-FAF5F36B6C80",
"updatedBy": "Sini "
},
{
"id": 59,
"code": "UK",
"name": "United Kingdom",
"recordVersion": "3512B084-8DB7-48F6-9E01-C0861E2A128D",
"updatedBy": "sinju "
}
];

const localizedData = source.map(item => ({text: item.name, value: item.id}));

console.log(localizedData )

了解 Array.prototype.map()下次会帮你的。

关于javascript - 如何将数组中的对象转换为特定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58967295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com