如何重命名数组内的对象键

Mil*_*los 19 javascript arrays object ecmascript-6

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

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' 
  },
]
Run Code Online (Sandbox Code Playgroud)

我想用这些键替换对象内的所有键:

const newKeys = [
   'firstname',
   'age',
   'weapon',
   'email',
   'city'
]
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?一个例子将不胜感激!

mic*_*ckl 13

您可以使用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);
Run Code Online (Sandbox Code Playgroud)