简体   繁体   English

根据序列化对象创建数组

[英]Create an array based off of a serialized object

Given a JavaScript object like this: (it has come from serialized form data) 给定这样一个JavaScript对象:(它来自序列化表格数据)

{
  "my_data[options][0][foo]": "a", 
  "my_data[options][0][bar]": "b",
  "my_data[options][1][foo]": "c",
  "my_data[options][1][bar]": "d",
  "my_data[options][2][foo]": "e",
  "my_data[options][2][bar]": "f"
}

How can I manipulate it so I end up with: 我该如何操纵它,最后得到:

[
  {foo: "a", bar: "b"},
  {foo: "c", bar: "d"},
  {foo: "e", bar: "f"}
]

While there are only 3 objects here, in practice there will be an unknown number of objects. 虽然这里只有3个对象,但实际上,对象的数量是未知的。

Edit: 编辑:
A little more info. 更多信息。

The reason I'm doing this is because I need to get data from form elements on the page. 我这样做的原因是因为我需要从页面上的表单元素获取数据。

<form>
  <input type="text" name="my_data[something]" />
  <input type="text" name="unrelated_thing" />

Within the form, I have a matrix full of fields like: 在表单中,我有一个充满字段的矩阵,例如:

<table>
  <tr>
    <td><input type="text" name="my_data[options][0][foo]" /></td>
    <td><input type="text" name="my_data[options][0][bar]" /></td>
  </tr>
  <tr>
    <td><input type="text" name="my_data[options][1][foo]" /></td>
    <td><input type="text" name="my_data[options][1][bar]" /></td>
  </tr>
  etc...
</table>

I need to get just the data from the matrix ( my_data[options] ) in an array so I can iterate over it. 我只需要从数组中的矩阵( my_data[options] )中获取数据,以便可以对其进行迭代。

I think serializing the form and then manipulating the data would be faster than iterating over each table row and then over each field. 我认为序列化表格然后处理数据要比遍历每个表行然后遍历每个字段更快。

Something like this: 像这样:

var res = [];
for(var i in mydata[options]) {
    res.push({foo: i[foo], bar: i[bar]});
}

I ended up just iterating over the tr s and then the input s inside. 我最终只是遍历了tr ,然后是内部的input
I used a str.replace with a regex to strip out the appropriate parts of the name attribute. 我使用带有正则表达式的str.replace来删除name属性的适当部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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