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.
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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.