0

I have an array of objects

var arr = [{id:1, animal:'dog'}, {id:3, animal:'tiger'}, {id:2, animal:'elephant'}, {id:5, animal:'cat'}];

I want to fetch ids from above array of object and make another array like

var idArray = [1,3,2,5]; 

Please suggest a concise es6 solution.

2 Answers 2

2

Use Array#map to iterate the array, and pluck the id using an arrow function, and destructuring for the ES6 flavor:

const arr = [{id:1, animal:'dog'}, {id:3, animal:'tiger'}, {id:2, animal:'elephant'}, {id:5, animal:'cat'}]

const result = arr.map(({ id }) => id);

console.log(result);

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

Comments

2

You can do it in one row using map (it will create new array, and will put id from every iteration through arr to idArray), here it is:

var arr = [{id:1, animal:'dog'}, {id:3, animal:'tiger'}, {id:2, animal:'elephant'}, {id:5, animal:'cat'}];

var idArray = arr.map(function(item) {return item.id});
console.log(idArray);

2 Comments

This answer is also correct, but answer from @ori is more es6.
@LokeshAgrawal, I agree, ES6 solutions with arrow functions are more elegant, but not all developers are using ES6, I based on this when wrote the answer.

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.