Build a JSON object from a string containing multidimensional

I have an array of name / value objects (below). Names are formatted to represent a multidimensional array.

I need to build a complete JavaScript object from 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" }] 

In something like this:

 {getQuote : { origin : Omaha}, { destination : 10005}, {vehicles : [ { year : 1989, make: Honda, model : accord }, { //etc }] 

n

+4
source share
1 answer

You can do it manually, for example:

 var source = [ /* Your source array here */ ]; var dest = {}; for(var i = 0; i < 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 is the resulting object.

Check if this works: http://jsfiddle.net/pnkDk/7/

+2
source

Source: https://habr.com/ru/post/1416175/


All Articles