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(',');
Sign up to request clarification or add additional context in comments.

10 Comments

tnx and this will return a string? and as a reminder I don't want my original companies array is modified
This will return a string. The original array will remain unmodified.
I think join uses a comma as a delimiter by default (you don't need to specify it)
@Spring If you have underscore use _.pluck(companies, "companyId").join() :)
No difference actually just more specific method to project data in arrays.
|
1

Try $.makeArray()

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

var expectedStringResult = $.makeArray(company.companyId).join();

2 Comments

it returns nothing :)
srry no time for that

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.