gpt4 book ai didi

javascript - 如何重命名数组中的对象键

转载 作者:行者123 更新时间:2023-12-01 14:44:52 24 4
gpt4 key购买 nike

我有一个这样的对象数组:

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);

关于javascript - 如何重命名数组中的对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63284616/

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