How can we convert this Javascript Array [li.one, li.one, li.one, li.two, li.two, li.two]
into a JSON array using JSON.stringify?
Using the following Javascript:
var stringsToStringify = $('.one, .two'),
stringArray = []
$.each(stringsToStringify, function (i, v) {
stringArray[i] = v
})
console.log(stringArray)
var jsonString = JSON.stringify(stringArray)
console.log(jsonString)
console.log(JSON.parse(jsonString))
Returns:
[li.one, li.one, li.one, li.two, li.two, li.two]
[{"jQuery110203514890133216494":1},{"jQuery110203514890133216494":2},{"jQuery110203514890133216494":3},{"jQuery110203514890133216494":4},{"jQuery110203514890133216494":5},{"jQuery110203514890133216494":6}]
[Object { jQuery110203514890133216494=1}, Object { jQuery110203514890133216494=2}, Object { jQuery110203514890133216494=3}, Object { jQuery110203514890133216494=4}, Object { jQuery110203514890133216494=5}, Object { jQuery110203514890133216494=6}]
If we change the stringArray
from []
to {}
the following is returned:
[li.one, li.one, li.one, li.two, li.two, li.two]
[{"jQuery110207305097851789301":1},{"jQuery110207305097851789301":2},{"jQuery110207305097851789301":3},{"jQuery110207305097851789301":4},{"jQuery110207305097851789301":5},{"jQuery110207305097851789301":6}]
[Object { jQuery110207305097851789301=1}, Object { jQuery110207305097851789301=2}, Object { jQuery110207305097851789301=3}, Object { jQuery110207305097851789301=4}, Object { jQuery110207305097851789301=5}, Object { jQuery110207305097851789301=6}]
The desired result is to have [li.one, li.one, li.one, li.two, li.two, li.two]
"stringified" into a JSON Array.
This looks like a circular reference. What is the best way to supply the array of html elements to JSON.stringify
?