Leon Gaban
Leon Gaban

Reputation: 39044

Taking key data from objects in Array and turning them into a , separated string

What method, or lodash function would you use to pull out the ids below and generate a comma separated string out of them?

var myArray = [
    {
        tag: 'wunwun',
        id: 132
    },
    {
        tag: 'davos',
        id: 452
    },
    {
        tag: 'jon snow',
        id: 678
    }
]

Like this: '132, '452', '678'

Upvotes: 1

Views: 32

Answers (4)

webdeb
webdeb

Reputation: 13211

Well, this is easy:

_.pluck(myArray, 'id').join(', ')

_.map works the same way, but you can also pass in a function instead of an array

Upvotes: 1

Rohit Shedage
Rohit Shedage

Reputation: 25930

myArray.map(function(element){return element.id;}).join(',');

Upvotes: 0

Rayon
Rayon

Reputation: 36609

Use Array#map to get array of id and apply Array#join over it.

var myArray = [{
  tag: 'wunwun',
  id: 132
}, {
  tag: 'davos',
  id: 452
}, {
  tag: 'jon snow',
  id: 678
}];
var op = myArray.map(function(item) {
  return item.id;
});
console.log(op.join(', '))

Upvotes: 2

TimoStaudinger
TimoStaudinger

Reputation: 42520

No need to use a third-party library for that:

var commaSeparatedIds = myArray.map(function(item) {
    return item.id;
}).join(','); // result: '132,452,678'

Or if you just want them as an array, skip the join:

var commaSeparatedIds = myArray.map(function(item) {
    return item.id;
}); // result: ['132', '452', '678']

References:

Upvotes: 2

Related Questions