3

Im trying to convert at object array with jQuery or javascript to a comma separated string, and no matter what I try I can´t get it right.

I have this from a select value.

ort = $('#ort').val();
ort=JSON.stringify(ort)

ort=["Varberg","Halmstad","Falkenberg"]

How can I convert it to a string looking like this?

ort=Varberg,Halmstad,Falkenberg

Any input appreciated, thanks.

3
  • 3
    use join() in example ["i", "am", "too", "lazy", "to", "search"].join(); will output "i,am,too,lazy,to,search" Commented Feb 2, 2019 at 18:04
  • 1
    you don't even need to explicitely join() you can simply convert it to a String. Like ""+["Varberg","Halmstad","Falkenberg"] or String(["Varberg","Halmstad","Falkenberg"]) or ["Varberg","Halmstad","Falkenberg"].toString() Commented Feb 2, 2019 at 18:09
  • That's a simple solution: let ortObjectToArray = JSON.parse(ort); let ortDecode = ortObjectToArray .join(','); Commented Sep 18, 2022 at 8:20

3 Answers 3

10

You can use join

let arr = ["Varberg","Halmstad","Falkenberg"]

console.log(arr.join(','))

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

7 Comments

Thanks, but Im getting an error, TypeError: ort.join is not a function. (In 'ort.join(',')', 'ort.join' is undefined) ?
you can use .join(). Default value for separator is ,
@ClaesGustavsson can you tell what console log of console.log(ort, typeof ort) shows ? without that it's possible to tell you exact reason.
@Cid thanks for pointing out mate, but i prefer this for the shake of readability :)
@ClaesGustavsson join is an array method. you need to parse string to array first you can use this JSON.parse(["Varberg","Halmstad","Falkenberg"]).join(',')
|
2

Use Array.prototype.join to to convert it into a comma separated string.

let str = ort=["Varberg","Halmstad","Falkenberg"].join(","); //"," not needed in join
console.log(str);

A simple toString also works in this case.

let str = ort=["Varberg","Halmstad","Falkenberg"].toString();
console.log(str);

2 Comments

you can use .join(). Default value for separator is ,
@Cid yes right!
0

Another way to achieve this is by using Array.prototype.reduce:

console.log(["Varberg", "Halmstad", "Falkenberg"].reduce((s, el, idx, arr) => {
  s += el
  if (idx < arr.length - 1) {
    s += ','
  }
  return s;
}, ''));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.