Sergio Lima
Sergio Lima

Reputation: 13

How to convert array of strings into JSON object?

I need to go back to a list page without lose the filters criteria. To do this, I'm using cookies, setting it when the form filter is submitted. In the list page mounted hookie, I'm getting the specific cookie as a string, using the split method and i have the result:

[
 "filter1:value",
 "filter2:value"
]

Or, an array of strings. How can i convert it to JSON to manipulate and insert each value in v-model of form filter?

*Is a web application using VueJS.

Upvotes: 1

Views: 4083

Answers (3)

carminePat
carminePat

Reputation: 159

With the first row we convert array to string, with the second row we convert String, to JSON object, you can manipulate

var arrayToString = JSON.stringify(Object.assign({}, arr));  // convert array to string
var stringToJsonObject = JSON.parse(arrayToString); 

Upvotes: 0

Akif Hadziabdic
Akif Hadziabdic

Reputation: 2900

You can use JSON.stringify and JSON.parse.

JSON.stringify({list: ["filter1:value", "filter2:value"]})
'{"list":["filter1:value","filter2:value"]}'
JSON.parse('{"list":["filter1:value","filter2:value"]}')
{list: ["filter1:value", "filter2:value"]}

Upvotes: 0

Alan Omar
Alan Omar

Reputation: 4227

use Object.fromEntries to construct an object out of your array elements after splitting them using : seperator:

let data = [
 "filter1:value",
 "filter2:value"
]

let result = Object.fromEntries(data.map(e => e.split(":")))

console.log(result)

Upvotes: 1

Related Questions