Theodore K. Theodore K. - 26 days ago 8
JSON Question

Convert string with index in brackets to JSON array

I have various strings with numbers in brackets like

"[4]Motherboard, [25]RAM"
how can I convert such a string to a JSON array (keeping both ids and values) like this:

{"data":[
{"id":"4","item":"Motherboard"},
{"id":"25","item":"RAM"}
]};


I'm tried using
split(",")
to create the array but I really can't find out how to get the inner data in this case.

Answer
function toArray(string) {
    return {
        data: string.split(",").map(function(str) {
            str = str.trim();
            return {
                id: str.substring(1, str.indexOf("]")),
                item: str.substring(str.indexOf("]") + 1),
            };
        }),
    };
}
Comments