1

I have an array of company objects and now I want to create a comma separated string of "companyId"s

 var company ={companyId:'', companyName:''}, 
 var companies: [company1, company2, ..]

 expectedStringResult ="companyId1,companyId2,companyId3"  

I see this example in SO:

Create comma-delimited string

But the answer assumes you have strings in your array and not objects like company, is there a way to neatly accomplish this without a for loop in javascript/jquery? (like you apply transform function in Java guava library)

Edit: I ended up using underscoreJS pluck function:

 _.pluck(companies, "companyId").join()

this does not crash if companies is null and much clean

But the accepted answer below with jQuery also works well.

2 Answers 2

3
companies.map(function(item){return item.companyId;}).join(',');

Or for old browsers

$.map(companies, function(item){return item.companyId;}).join(',');
10
  • tnx and this will return a string? and as a reminder I don't want my original companies array is modified
    – Spring
    Dec 5, 2013 at 14:43
  • This will return a string. The original array will remain unmodified. Dec 5, 2013 at 14:44
  • I think join uses a comma as a delimiter by default (you don't need to specify it)
    – jbabey
    Dec 5, 2013 at 14:44
  • 1
    @Spring If you have underscore use _.pluck(companies, "companyId").join() :) Dec 5, 2013 at 15:31
  • 1
    No difference actually just more specific method to project data in arrays. Dec 5, 2013 at 15:34
1

Try $.makeArray()

Convert an array-like object into a true JavaScript array.

var expectedStringResult = $.makeArray(company.companyId).join();
2
  • it returns nothing :)
    – Spring
    Dec 5, 2013 at 15:00
  • srry no time for that
    – Spring
    Dec 5, 2013 at 15:08

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.