Jack
Jack

Reputation: 329

pick multiple keys and values from array of objects

I need to pick few keys and values (only name and age) from below array of objects.

const studentList = [{"id": "1", "name": "s1". "age": 10, "gender" : "m", "subject": "Maths"},{"id": "2", "name": "s2". "age": 11, "gender" : "m", "subject": "Maths"}]

I can achieve that using map and lodash pick as in below.

let nameAndAgeList = studentList.map(student => pick(student, ["name", "age"]));

But is there any more easy way with only using map. I know we can retrieve only one property as in below.

let nameArr = (studentList).map(({ name }) => name);

But how can we retrieve both name and age using map? Or any more easy & best ways with es6+

Upvotes: 0

Views: 9390

Answers (2)

KooiInc
KooiInc

Reputation: 122906

The studentList assignment is not valid (it contains dots instead of comma). Corrected in the snippet. You can map name and age in one go using:

const studentList = [
  {"id": "1", "name": "s1", "age": 10, "gender" : "m", "subject": "Maths"},
  {"id": "2", "name": "s2", "age": 11, "gender" : "m", "subject": "Maths"}];
console.log( studentList.map( ({name, age}) => ({name, age}) ) );

Upvotes: 2

Rickard Elimää
Rickard Elimää

Reputation: 7591

You can retrieve multiple properties, just like in the example below.

const studentList = [{"id": "1", "name": "s1", "age": 10, "gender" : "m", "subject": "Maths"},{"id": "2", "name": "s2", "age": 11, "gender" : "m", "subject": "Maths"}]

let nameArr = (studentList).map(({ name, age }) => {
  return {'name': name, 'age': age}
});

console.log(nameArr)

Upvotes: 1

Related Questions