javascript - Build JSON Object from string containing multi-dimensional -
i have array of name/value objects (below). names formatted represent multi-dimensional array.
i need build full javascript object out of it(bottom).
[{ name: "getquote[origin]", value: "omaha,ne" }, { name: "getquote[destination]", value: "10005" }, { name: "getquote[country]", value: "us" }, { name: "getquote[vehicles][0][year]", value: "1989" }, { name: "getquote[vehicles][0][make]", value: "daihatsu" }, { name: "getquote[vehicles][0][model]", value: "charade" }, { name: "getquote[vehicles][0][count]", value: "1" }] into this:
{getquote : { origin : omaha}, { destination : 10005}, {vehicles : [ { year : 1989, make: honda, model : accord }, { //etc }] n
you can manually, this:
var source = [ /* source array here */ ]; var dest = {}; for(var = 0; < source.length; i++) { var value = source[i].value; var path = source[i].name.split(/[\[\]]+/); var curitem = dest; for(var j = 0; j < path.length - 2; j++) { if(!(path[j] in curitem)) { curitem[path[j]] = {}; } curitem = curitem[path[j]]; } curitem[path[j]] = value; } dest resulting object.
check working here: http://jsfiddle.net/pnkdk/7/
Comments
Post a Comment