3

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?

3 Answers 3

3

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);

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

Comments

3

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(', '))

Comments

1

It should be accessible with the name of the object and dot notation:

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

You could get this with:

obj.data

2 Comments

I edited the code to be clearer above. Dot notation uses the name of the object followed by a dot, followed by the name of the property you are trying to get. You can save obj.data to a variable like this: let data = obj.data;
You're welcome. Here is the documentation for how this sort of thing works: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.