1

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'

4 Answers 4

2

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(', '))

Sign up to request clarification or add additional context in comments.

1 Comment

No need of join, just call toString.
2

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:

Comments

1

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

2 Comments

Also just used this: var terms = _.map(alertSettings.fav_tags, function (tag) { return tag.term_id; });
You don't need the function, you can also just apply the key
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.