简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM