Как переименовать ключи объекта внутри массива - PullRequest
18 голосов
/ 06 августа 2020

У меня есть массив таких объектов:

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

Как лучше всего сделать этот? Будем признательны за пример!

Ответы [ 11 ]

1 голос
/ 12 августа 2020

Другой вариант: использование replace при поиске имен свойств в строковом customers с последующим синтаксическим анализом до JSON:

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 = [
   {from: 'customer_name', to:'firstname'},
   {from: 'customer_age', to:'age'},
   {from: 'customer_weapon', to:'weapon'},
   {from: 'customer_email', to:'email'},
   {from: 'customer_city', to:'city'}
]


let str = JSON.stringify(customers);

newKeys.forEach(o=>str = str.replace(new RegExp(o.from, 'g'), o.to));

console.log(JSON.parse(str));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...