我有从服务中获得的这个数组:
dataFromServer = [
{
created_date: "02/10/2019"
date_of_birth: "01/01/2000"
email: "[email protected]"
first_name: "test"
last_name: "test"
mobile_phone: "999-999-9999"
registration_id: "3344"
},
{
created_date: "02/10/2015"
date_of_birth: "01/01/1980"
email: "[email protected]"
first_name: "test2"
last_name: "test2"
mobile_phone: "111-222-333"
registration_id: "123"
}
]
我必须把它放在另一个数组中以摆脱每个属性之间的“_”。所以这就是我正在做的:
const newArray = []
dataFromServer.foreach(obj => {
newArray.push(
{
lastName: obj.last_name,
firstName: obj.first_name,
dateOfBirth: obj.date_of_birth,
registrationId: obj.registration_id,
createdDate: obj.created_date,
email: obj.email,
mobile_phone: obj.mobile_phone
});
});
在纯 javascript(可能使用解构)或使用 Lodash 中是否有更好/清晰的方法?非常感谢!
是的,您可以使用map
, 或许(使用 ES2015+)和箭头函数:
const newArray = dataFromServer.map(obj => ({
lastName: obj.last_name,
firstName: obj.first_name,
dateOfBirth: obj.date_of_birth,
registrationId: obj.registration_id,
createdDate: obj.created_date,
email: obj.email,
mobile_phone: obj.mobile_phone
}));
现场示例:
const dataFromServer = [
{
created_date: "02/10/2019",
date_of_birth: "01/01/2000",
email: "[email protected]",
first_name: "test",
last_name: "test",
mobile_phone: "999-999-9999",
registration_id: "3344"
},
{
created_date: "02/10/2015",
date_of_birth: "01/01/1980",
email: "[email protected]",
first_name: "test2",
last_name: "test2",
mobile_phone: "111-222-333",
registration_id: "123"
}
];
const newArray = dataFromServer.map(obj => ({
lastName: obj.last_name,
firstName: obj.first_name,
dateOfBirth: obj.date_of_birth,
registrationId: obj.registration_id,
createdDate: obj.created_date,
email: obj.email,
mobile_phone: obj.mobile_phone
}));
console.log(newArray);
.as-console-wrapper {
max-height: 100% !important;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句