0

I have an array of string for example like this:

var names = ["sam", "john", "tom", "travis", "jack"]

And I need to create JavaScript object which will contain all these names separated by , by one key.

Look what I want:

var obj = {names : "sam, john, tom, travis, jack"}

I'm not familiar with JavaScript. I understand that I need to loop through my array of string and somehow append values to my object.

I am using jQuery if there's something in that which would help.

5
  • 1
    did you make any attempt so far? do you have some code to improve? Commented Dec 22, 2014 at 8:53
  • why do you even want to do this? You have more control over an array than a comma separated list Commented Dec 22, 2014 at 8:54
  • Note that that isn't multiple values for one key. It's a single value: A string. Commented Dec 22, 2014 at 8:55
  • 1
    Why not use use var obj = {names : ["sam", "john", "tom", "travis", "jack"]}? Commented Dec 22, 2014 at 9:05
  • Frankly, that's a single line of simple JavaScript, but you do not give the impression you've actually tried. Check out "join" on mdn. Commented Dec 22, 2014 at 11:07

3 Answers 3

5

Well, sure you could use Array.join

var obj = { names: names.join(", ") };

MDN

Summary

The join() method joins all elements of an array into a string.

Syntax

str = arr.join([separator = ','])

separator Optional. Specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma.

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

Comments

1

Use .toString() in javascript.The toString() method converts an array into a String and returns the result.The returned string will separate the elements in the array with commas.

var obj = { names : names.toString() };

FIDDLE

Comments

0

jap use join...

var obj = { names: names.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.