Steve Reichbach
Steve Reichbach

Reputation: 98

convert key value pairs into array javascript

I have an object that I receive from html form, and it has the following syntax:

  'ingredients[0][name]': 'eggplant',
  'ingredients[0][mass]': '1',
  'ingredients[0][units]': 'pc',
  'ingredients[1][name]': 'cheese',
  'ingredients[1][mass]': '150',
  'ingredients[1][units]': 'gr',
  'ingredients[2][name]': 'cilantro',
  'ingredients[2][mass]': '100',
  'ingredients[2][units]': 'tt' ...

All that I need is to convert these key-value pairs into the one big object field. Such as

recipe = {
    ingredients: [
        {
            name: 'epplant',
            mass: '1',
            units: 'pc'
        },
        {
            name: 'cheese',
            mass: '150',
            units: 'gr'
        }, ...
    ]
}

How can I do this without JQuery or other JS-framework?

Upvotes: 0

Views: 736

Answers (1)

var form = {
  'ingredients[0][name]': 'eggplant',
  'ingredients[0][mass]': '1',
  'ingredients[0][units]': 'pc',
  'ingredients[1][name]': 'cheese',
  'ingredients[1][mass]': '150',
  'ingredients[1][units]': 'gr',
  'ingredients[2][name]': 'cilantro',
  'ingredients[2][mass]': '100',
  'ingredients[2][units]': 'tt'
}

var re = /([a-zA-Z][a-zA-Z_0-9]*)\[(\d+)\]\[([a-zA-Z][a-zA-Z0-9_]*)\]/

var result = {}

for (var key in form) {
    var match = key.match(re)
    if (!match) continue
    var arr = result[match[1]]
    if (!arr) arr = result[match[1]] = []
    var obj = arr[match[2]]
    if (!obj) obj = arr[match[2]] = {}
    obj[match[3]] = form[key]
}

console.log(result)

http://jsfiddle.net/r1gkog1b/

UPD: some explanation:

I think, you should iterate throw your input form object keys and parse its with regexp. In case of match you can construct desirable output structure

Upvotes: 2

Related Questions