javascript - 如何重命名数组中的对象键
问题描述
我有一个这样的对象数组:
const customers = [
{
customer_name: 'Negan',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
},
{
customer_name: 'Daryl',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
},
]
我想用这些键替换对象内的所有键:
const newKeys = [
'firstname',
'age',
'weapon',
'email',
'city'
]
做这个的最好方式是什么?一个例子将不胜感激!
解决方案
您可以使用它Object.values()
来检索值,然后array.reduce()
组成一个新对象:
const customers = [
{
customer_name: 'Negan',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
},
{
customer_name: 'Daryl',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
},
];
const newKeys = [
'firstname',
'age',
'weapon',
'email',
'city'
];
let result = customers.map(obj =>
Object.values(obj).reduce((acc, cur, i) => {
acc[newKeys[i]] = cur;
return acc; }, {}));
console.log(result);
推荐阅读
- jenkins - 即使 jmeter 持续时间断言失败,Jenkins 构建也会通过
- java - 是否可以使用java方法返回“如果条件满足返回列表,否则返回错误消息”
- algorithm - 如何在我的二进制搜索实现中找出循环不变量?
- java - 在JSP中用商标替换单词
- amazon-web-services - 从不同的 s3 区域恢复弹性搜索快照
- html - 如何在 Adobe Dreamweaver 中删除相关文件
- c++ - Boost::Asio 异步聊天客户端停止与服务器通信
- android - 在改造请求中使用额外的 nameValuePair 格式化 JSON
- elasticsearch - 如何将日志收集到 Elasticsearch
- go - 无法与 HTTP 代理连接