javascript - 将键值对转换为数组javascript

标签 javascript arrays object

我有一个从 html 表单收到的对象,它具有以下语法:

  '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' ...

我所需要的就是将这些键值对转换为一个大对象字段。比如

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

如果没有 JQuery 或其他 JS 框架,我该如何做到这一点?

最佳答案

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:一些解释:

我认为,您应该迭代抛出输入表单对象键并使用正则表达式解析它。如果匹配,您可以构建所需的输出结构

关于javascript - 将键值对转换为数组javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349552/

相关文章:

javascript - 获取一组背景图像以供稍后保存,然后在它们和背景颜色之间悬停切换

javascript - jQuery无法获取data-*属性值,返回undefined

javascript - jQuery 检查任何文本输入是否有值(value)

php - 将数组插入 MySQL DB(意外的 T_STRING)

javascript - 具有多个对象的 jquery extend() 如何工作?

javascript - Node.JS 对象创建问题 "User is not a function"

javascript - 带有局部参数的 onclick 全局函数

python - Numpy 2d 和可能的 N d 通过元组数组进行索引

javascript - 使用 Ramda.js 基于数组过滤对象

java - 在另一个类中使用字符串