0

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+

Jack
  • 259
  • 4
  • 18
  • Could you share the expected output? Is it an array of objects with `name` and `age` props? If yes, `const nameAgeList = studentList.map(({name, age, ...rest}) => ({name, age}));` <-- this may be helpful. Please try. – jsN00b Mar 27 '22 at 11:46
  • yes, which is exactly return by `nameAndAgeList` in above. – Jack Mar 27 '22 at 11:47
  • 1
    Please fix the first example as it does not encompass valid syntax. The ```.``` should be replaced by ```,```. – Ovidijus Parsiunas Mar 27 '22 at 11:51
  • This is essentially the same question as [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). – Dan Dascalescu Apr 07 '22 at 11:55

2 Answers2

2

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}) ) );
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

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)
Rickard Elimää
  • 7,107
  • 3
  • 14
  • 30