Home > Back-end >  How to split up JSON object from express into an array
How to split up JSON object from express into an array

Time:05-31

I am unsure how to clean up a returned JSON object into an array. I would like to split up and remove the extraneous punctuation from the recipe_method property of a JSON object returned from my DB.

The recipe_method data below is POSTed to server as an array:

['Boil water', 'put pasta in water', 'make sauce']
Array(1)
0:
id: 17
recipe_method: "{\"Boil water\",\"Put pasta in water\",\"Make sauce\"}" //this is what I want to clean
recipe_name: "123pasta"
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)

Ideally it would be cleaned up and split up to be this array:

['Boil water', 'put pasta in water', 'make sauce']

CodePudding user response:

You can use slice the string and remove the unwanted brackets. Then split the string into array.

recipe_method.slice(2,a.length-2).split('","') // ['Boil water', 'Put pasta in water', 'Make sauce']

CodePudding user response:

As there is no such data structure in JavaScript you can replace the curly braces with square ones and then parse it as a JSON.

let recipe_method = "{\"Boil water\",\"Put pasta in water\",\"Make sauce\"}"

function parse_recipe(recipe) {
    return JSON.parse(recipe.replace('{', '[').replace('}', ']'))
}

parse_recipe(recipe_method)  // ['Boil water', 'put pasta in water', 'make sauce']
  • Related