Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return objects in array as string with comma ?

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?

like image 959
egemen Avatar asked Nov 25 '25 20:11

egemen


2 Answers

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()
like image 164
commadelimited Avatar answered Nov 28 '25 11:11

commadelimited


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.

like image 43
Patrick Gunderson Avatar answered Nov 28 '25 09:11

Patrick Gunderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!