如何从数组中提取值并将其存储在另一个数组中?

时间:2019-02-28 14:11:50

标签: javascript lodash

我从发球区得到了这个数组:

dataFromServer = [
 {
  created_date: "02/10/2019"
  date_of_birth: "01/01/2000"
  email: "test@test.com"
  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: "test2@test2.com"
  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中是否有更好/清晰的方法?非常感谢!

2 个答案:

答案 0 :(得分:0)

是的,您可以结合使用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: "test@test.com",
  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: "test2@test2.com",
  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;
}

答案 1 :(得分:-2)

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
    }));