Reputation: 39044
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
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
Reputation: 25930
myArray.map(function(element){return element.id;}).join(',');
Upvotes: 0
Reputation: 36609
Use
Array#map
to get array ofid
and applyArray#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
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