admin管理员组

文章数量:1336632

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.

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.

Share Improve this question edited May 11, 2016 at 8:35 winhowes 8,0955 gold badges31 silver badges41 bronze badges asked May 10, 2016 at 23:02 Jake NJake N 10.6k12 gold badges67 silver badges114 bronze badges 2
  • If you want to use a library, go for lodash (lodash./docs#flatten). Though you might have to find a function which works for your case. – Vikram Tiwari Commented May 10, 2016 at 23:33
  • Thanks for the suggestion. I don't need to use a library, just thought that it's the kind of that that a library might be useful for. – Jake N Commented May 11, 2016 at 8:33
Add a ment  | 

1 Answer 1

Reset to default 7

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.

本文标签: javascriptGet object values from arrayNodeJsStack Overflow