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+

4
  • 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. Commented Mar 27, 2022 at 11:46
  • yes, which is exactly return by nameAndAgeList in above. Commented Mar 27, 2022 at 11:47
  • 1
    Please fix the first example as it does not encompass valid syntax. The . should be replaced by ,. Commented Mar 27, 2022 at 11:51
  • This is essentially the same question as How to get a subset of a javascript object's properties. Commented Apr 7, 2022 at 11:55

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.