Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to get comma separated string from json string?

I have a JSON string value that corresponds to this object:

{
"id" : "122223232244",
"title" : "התרעת פיקוד העורף",
"data" : ["עוטף עזה 218","עוטף עזה 217"]
}

I am trying to extract the following value from the object above, so that the data array is joined together as a single comma separated string like this:

"עוטף עזה 218,עוטף עזה 217"

How can this be done?

like image 720
IcePyro Avatar asked Nov 17 '25 09:11

IcePyro


2 Answers

This can be achieved via the join() method which is built into the Array type:

const object = {
"id" : "122223232244",
"title" : "התרעת פיקוד העורף",
"data" : ["עוטף עזה 218","עוטף עזה 217"]
}

/* Join elements of data array in object to a comma separated string */
const value = object.data.join();

console.log(value);

If no separator argument is supplied, then the join() method will default to use a comma separator by default.

Update

If the JSON was supplied in raw text via a string you can use the JSON.parse() method to extract an object from the JSON string value as a first step like so:

const json = `{"id" : "122223232244","title" : "התרעת פיקוד העורף","data" : ["עוטף עזה 218","עוטף עזה 217"]}`

/* Parse input JSON string */
const object = JSON.parse(json);

/* Join elements of data array in object to a comma separated string */
const value = object.data.join();

console.log(value);
like image 183
Dacre Denny Avatar answered Nov 20 '25 01:11

Dacre Denny


Access object properties using dot notation (e.g. obj.data) and then on the array you can use join to convert to a string with a comma in between.

const obj = {
    "id" : "122223232244",
    "title" : "התרעת פיקוד העורף",
    "data" : ["עוטף עזה 218","עוטף עזה 217"]
}

console.log(obj.data.join(', '))
like image 25
noetix Avatar answered Nov 20 '25 01:11

noetix



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!