首页 > 解决方案 > 如何重命名数组中的对象键

问题描述

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

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'
]

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

标签: javascriptarraysobjectecmascript-6

解决方案


您可以使用它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);


推荐阅读