简体   繁体   English

Map 特定属性从一个数组变成一个新数组

[英]Map specific properties from an array into a new array

I have the following array of employees.我有以下员工。 I want to create a new array employeeNames that has only the firstName and lastName properties.我想创建一个只有 firstName 和 lastName 属性的新数组employeeNames I believe I can do this with the map() method but I'm not exactly sure how.我相信我可以用map()方法做到这一点,但我不完全确定如何。

let employees = { firstName: 'Collin', lastName: 'Sexton', email: 'exampe@test.com', dob: '03/20/1986' ... }

Resulting array should look like:结果数组应如下所示:

employeeNames = { firstName: 'Collin', lastName: 'Sexton' }

You are not looking for array as a result though.. do this结果你不是在寻找数组..这样做

let { firstName, lastName } = employees;
let employeeNames = { firstName, lastName };

What we do here is called deconstruction.我们在这里所做的称为解构。 We bind the values of 'firstName' and 'lastName' to variables with the same name and then create a new Object with those variables.我们将“firstName”和“lastName”的值绑定到具有相同名称的变量,然后使用这些变量创建一个新的 Object。 If no keys are given, it automagically names them after the variables.如果没有给出键,它会自动在变量之后命名它们。

employees is an object which is not iterable, so you need to convert before being able to map() a new one. employees 是一个不可迭代的 object,因此您需要先转换才能map()一个新的。

Which can easity be made with Object.entries() Object.entries()可以轻松实现

so..所以..

// key is the object key while value is the object value of corresponding key
let newArray = Object.entries(employees).map((key, value) => {
   let arrayEntry;
   if (key === 'firstName' || key === 'lastName') {
      newEntry = value;
   }
   return arrayEntry;
});

Your new array should then output to [John, Doe, Jane, Doe, name, lastname]然后,您的新阵列应该 output 到[John, Doe, Jane, Doe, name, lastname]

Probably you meant you have array of objects.可能你的意思是你有对象数组。 So you'd do:所以你会这样做:

const projected = empArray.map((empItem) => ({
    firstName: empItem.firstName,
    lastName: empItem.lastName,
}));

Here is how it will be if you need to map array of eployees to array with only needed props:如果您需要 map 员工阵列以仅使用所需的道具进行阵列,情况如下:

let employees = [{ firstName: 'Collin', lastName: 'Sexton', email: 'exampe@test.com', dob: '03/20/1986'}]
let result = employees.map({firstName, lastName}=> ({ firstName, lastName}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM