我有一个这样的对象数组:
const customers = [
{
customer_name: 'Negan Lucille',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: '[email protected]',
customer_city: 'Washington'
},
{
customer_name: 'Daryl Dixon',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: '[email protected]',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick Grimes',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: '[email protected]',
customer_city: 'King County'
},
];
并且我想将customer_name
名字和姓氏分开,因此名字应保留在其中customer_name
,姓氏应放在新创建的property中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: '[email protected]',
city: 'Washington'
},
{
firstname: 'Daryl',
lastname: 'Dixon',
age: 41,
weapon: 'Crossbow',
email: '[email protected]',
city: 'Atlanta'
},
{
firstname: 'Rick',
lastname: 'Grimes',
age: 45,
weapon: 'Magnum 357',
email: '[email protected]',
city: 'King County'
},
]
做这个的最好方式是什么?一个例子,将不胜感激!
使用split()
打破了名称,添加新的特性,然后删除旧属性。
const customers = [
{
customer_name: 'Negan Lucille',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: '[email protected]',
customer_city: 'Washington'
},
{
customer_name: 'Daryl Dixon',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: '[email protected]',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick Grimes',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: '[email protected]',
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句