简体   繁体   中英

Get object values from array - NodeJs

I have this array of objects

[ { id: '573267d06b2957ab24c54d59' },
  { id: '573267d06b2957ab24c54d5a' },
  { id: '573267d06b2957ab24c54d5b' },
  { id: '573267d06b2957ab24c54d5c' },
  { id: '573267d06b2957ab24c54d5d' } 
]

I wish to convert it to the following in NodeJs

[ '573267d06b2957ab24c54d59',
  '573267d06b2957ab24c54d5a',
  '573267d06b2957ab24c54d5b',
  '573267d06b2957ab24c54d5c',
  '573267d06b2957ab24c54d5d'
]

It seems like it should be easy given the right library/package, but I am struggling to find the right wording to "flatten" the array into the IDs of the contained objects.

Say your array of objects is called arr , just do this:

var arrayOfStrings = arr.map(function(obj) {
    return obj.id;
});

map will iterate over the array and create a new array based on how you define your function. In this case we return the value of the id key in each case to build out the desired array of ids.

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