简体   繁体   中英

How to get property from object array?

I have this array:

var arr1 = [{id:124,name:'qqq'}, 
           {id:589,name:'www'}, 
           {id:45,name:'eee'},
           {id:567,name:'rrr'}]

I need to get all Id's.

var Id's = [124,589,45,567];

What's the elegant way to retrieve all id's property from object array?

Use Array#map

The map() method creates a new array with the results of calling a provided function on every element in this array.

 var arr1 = [{ id: 124, name: 'qqq' }, { id: 589, name: 'www' }, { id: 45, name: 'eee' }, { id: 567, name: 'rrr' }]; var op = arr1.map(function(item) { return item.id; }); //Using Arrow functions `arr1.map((item) => (item.id));` console.log(op); 

尝试这个

var output = arr1.map(function(obj){ return obj.id; })
var result = arr1.map(function(obj) {
   return obj.id
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM