0

I have the following array of employees. I want to create a new array employeeNames that has only the firstName and lastName properties. I believe I can do this with the map() method but I'm not exactly sure how.

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

Resulting array should look like:

employeeNames = { firstName: 'Collin', lastName: 'Sexton' }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
noclist
  • 1,659
  • 2
  • 25
  • 66
  • 2
    But what you have shared is an object? Can you clarify your question – Hassan Imam Feb 03 '21 at 18:53
  • In case, you have valid array, then you need something like this `employees.map(({firstName, lastName}) => ({firstName, lastName}))` – Hassan Imam Feb 03 '21 at 18:55
  • Does this answer your question? [How to get a subset of a javascript object's properties](https://stackoverflow.com/questions/17781472/how-to-get-a-subset-of-a-javascript-objects-properties) – Heretic Monkey Feb 03 '21 at 19:01

4 Answers4

1

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. If no keys are given, it automagically names them after the variables.

zergski
  • 793
  • 3
  • 10
0

employees is an object which is not iterable, so you need to convert before being able to map() a new one.

Which can easity be made with 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]

zergski
  • 793
  • 3
  • 10
0

Probably you meant you have array of objects. So you'd do:

const projected = empArray.map((empItem) => ({
    firstName: empItem.firstName,
    lastName: empItem.lastName,
}));
Tal Rofe
  • 457
  • 12
  • 46
-1

Here is how it will be if you need to map array of eployees to array with only needed props:

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