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

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

const customers = [
    {
        customer_name: 'Negan Lucille', 
        customer_age: 45, 
        customer_weapon: 'Bat',
        customer_email: 'negan@sanctuary.com',
        customer_city: 'Washington' 
    },
    {
        customer_name: 'Daryl Dixon', 
        customer_age: 41, 
        customer_weapon: 'Crossbow',
        customer_email: 'daryl.dixon@kickass.com',
        customer_city: 'Atlanta' 
    },
    {
        customer_name: 'Rick Grimes', 
        customer_age: 45, 
        customer_weapon: 'Magnum 357',
        customer_email: 'rick@alexandria.com',
        customer_city: 'King County' 
    },
];

, и я хочу разделить customer_name на имя и фамилию, поэтому имя должно оставаться в customer_name, а последнее имя должно быть помещено во вновь созданное свойство customer_last_name. Также у меня есть массив newKeys, который я использую для замены текущих ключей в объектах customers, например:

const newKeys = [
   'firstname',
   'lastname',
   'age',
   'weapon',
   'email',
   'city'
]

let newCustomers = customers.map(obj => 
    Object.values(obj).reduce((acc, cur, i) => { 
       acc[newKeys[i]] = cur; 
       return acc; }, {}));

, и новый массив должен выглядеть так:

customers = [
  {
    firstname: 'Negan',
    lastname: 'Lucille', 
    age: 45, 
    weapon: 'Bat',
    email: 'negan@sanctuary.com',
    city: 'Washington' 
  },
  {
    firstname: 'Daryl', 
    lastname: 'Dixon',
    age: 41, 
    weapon: 'Crossbow',
    email: 'daryl.dixon@kickass.com',
    city: 'Atlanta' 
  },
  {
    firstname: 'Rick', 
    lastname: 'Grimes',
    age: 45, 
    weapon: 'Magnum 357',
    email: 'rick@alexandria.com',
    city: 'King County' 
  },
]

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

Ответы [ 3 ]

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

Используйте split(), чтобы разбить имя, добавить новые свойства, а затем удалить старое свойство.

const customers = [
    {
        customer_name: 'Negan Lucille', 
        customer_age: 45, 
        customer_weapon: 'Bat',
        customer_email: 'negan@sanctuary.com',
        customer_city: 'Washington' 
    },
    {
        customer_name: 'Daryl Dixon', 
        customer_age: 41, 
        customer_weapon: 'Crossbow',
        customer_email: 'daryl.dixon@kickass.com',
        customer_city: 'Atlanta' 
    },
    {
        customer_name: 'Rick Grimes', 
        customer_age: 45, 
        customer_weapon: 'Magnum 357',
        customer_email: 'rick@alexandria.com',
        customer_city: 'King County' 
    },
];

const refactored = customers.map(customer=>{
  var [firstname, lastname] = customer.customer_name.split(/\s/);
  return {
    firstname, lastname,
    age: customer.customer_age,
    weapon: customer.customer_weapon,
    email: customer.customer_email,
    city: customer.customer_city
  }
});

console.log(refactored);
1 голос
/ 06 августа 2020

Предполагая, что в имени нет пробела, вы можете использовать string.split

Затем вы можете использовать Array.prototype.shift , чтобы получить первый элемент и объединяют остальные вместе.

В моем примере я изменил имя на фамилию с двумя словами в качестве демонстрации

const customers = [
    {
        customer_name: 'Negan De Lucille', 
        customer_age: 45, 
        customer_weapon: 'Bat',
        customer_email: 'negan@sanctuary.com',
        customer_city: 'Washington' 
    },
    {
        customer_name: 'Daryl Dixon', 
        customer_age: 41, 
        customer_weapon: 'Crossbow',
        customer_email: 'daryl.dixon@kickass.com',
        customer_city: 'Atlanta' 
    },
    {
        customer_name: 'Rick Grimes', 
        customer_age: 45, 
        customer_weapon: 'Magnum 357',
        customer_email: 'rick@alexandria.com',
        customer_city: 'King County' 
    },
];

for (const i in customers) {
  const names = customers[i].customer_name.split(" ");
  const newCustomer = {
    age: customers[i].customer_age
    //add in the other properties
  }
  newCustomer.firstname = names.shift();
  newCustomer.lastname = names.join(" ");
  customers[i] = newCustomer;
};

console.log(customers);
0 голосов
/ 06 августа 2020

const customers = [
    {
        customer_name: 'Negan Lucille', 
        customer_age: 45, 
        customer_weapon: 'Bat',
        customer_email: 'negan@sanctuary.com',
        customer_city: 'Washington' 
    },
    {
        customer_name: 'Daryl Dixon', 
        customer_age: 41, 
        customer_weapon: 'Crossbow',
        customer_email: 'daryl.dixon@kickass.com',
        customer_city: 'Atlanta' 
    },
    {
        customer_name: 'Rick Grimes', 
        customer_age: 45, 
        customer_weapon: 'Magnum 357',
        customer_email: 'rick@alexandria.com',
        customer_city: 'King County' 
    },
];

for(let i=0;i<customers.length;i++){
   let name = customers[i].customer_name.split(' ')  
   customers[i].customer_name=name[0]
   customers[i].customer_last=name[1]  
   
   }
   
   console.log(customers)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...