3

var list = [ { id : 1234, shop : 'shop1' }, { id : 4312, shop : 'shop2' } ];

I want that only id attributes in object array return as "1234,4312". How can I do?

3
  • pluck the ids in a loop, and then join them to a string by commata? Have you tried? Commented Jun 5, 2014 at 21:20
  • 1
    Divide it up into individual tasks. You want to get the id attributes of objects in an array, and you want to join several things with a comma. Which is these tasks do you not know how to do? Commented Jun 5, 2014 at 21:21
  • Yes, but it is not easy way. I want to find out easier and alternative methods. Commented Jun 5, 2014 at 21:30

2 Answers 2

4

Even easier:

var list = [ { id : 1234, shop : 'shop1' }, { id : 4312, shop : 'shop2' } ];
ids = list.map(function(obj){
    return obj.id
})

If you specifically need a string, add a .toString() to the end of the map call:

ids = list.map(function(obj){
    return obj.id
}).toString()
Sign up to request clarification or add additional context in comments.

1 Comment

OP requires the result to be a commadelimited string.
1

You have to loop through the array and create a new array. It's actually not that hard:

var list = [ { id : 1234, shop : 'shop1' }, { id : 4312, shop : 'shop2' } ];
var ids = [];
list.forEach(function(obj, index){
    ids.push(obj.id);
});

if you want that as a comma delimited string you can simply call ids.toString(); it's the default behavior.

1 Comment

You really should use map instead of forEach. Also, OP requires the result to be a string.

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.