最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript: How to get comma separated string from json string? - Stack Overflow

programmeradmin1浏览0评论

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 ma separated string like this:

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

How can this be done?

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 ma separated string like this:

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

How can this be done?

Share Improve this question edited Jun 13, 2019 at 4:18 Dacre Denny 30.4k5 gold badges51 silver badges66 bronze badges asked Jun 13, 2019 at 3:56 IcePyroIcePyro 291 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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 ma 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 ma 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 ma separated string */
const value = object.data.join();

console.log(value);

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 ma in between.

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

console.log(obj.data.join(', '))

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
发布评论

评论列表(0)

  1. 暂无评论