Reputation: 5117
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.
Upvotes: 0
Views: 68
Reputation: 191976
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);
Upvotes: 2
Reputation: 16384
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);
Upvotes: 2