0

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?

2
  • 2
    what type of object you recieve from the form.is it a javascript object? Commented Aug 17, 2014 at 13:28
  • yep, it is an JS object, like form = { key1: value1, key2: value2 } and so on Commented Aug 17, 2014 at 15:03

1 Answer 1

2
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

Sign up to request clarification or add additional context in comments.

3 Comments

Please don't just post answers, but explain what they are doing.
Thanks, Alexey @Алексей-Овчинников ! That's a great idea, because I have other fields and need them to be converted into an JS Object fields. But I'm not sure about performance - I heard that regular expressions aren't fast.
regarding permormance - I think that there are only one way is to parse key with regexp (in case you need some unification) and my code have precompiled regexp so this is a faster possible way

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.