1

Problem:

Given that I have the following "name" and "value" strings:

<input type="text" name="attributes[options][0][label]" value="Test Option">
<input type="text" name="attributes[options][0][value]" value="test-option">

<input type="text" name="attributes[options][1][label]" value="Another Test Option">
<input type="text" name="attributes[options][1][value]" value="another-test-option">

How do I convert to the following JSON format?

attributes: {
    options: [
        {
            label: "Test Option",
            value: "test-option",
        },
        {
            label: "Another Test Option",
            value: "another-test-option",
        },
    ],
}
Jeff
  • 2,018
  • 2
  • 15
  • 18
  • You probably shouldn't be having to do something this convoluted in the first place – CertainPerformance Jun 01 '18 at 00:51
  • Describe what have you already tried and why didn't it work. – mentallurg Jun 01 '18 at 00:59
  • @mentallurg: How to try when you have no idea from where to start with – Isaac Jun 01 '18 at 01:18
  • I don't think there's any simple Javascript method for this. If you post the data to a server, they have libraries that will parse it. E.g. PHP will create that kind of structure in `$_POST`. – Barmar Jun 01 '18 at 01:57
  • See https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key for how to access an object using path strings like this. Similar techniques can be used to create the object in the first place. – Barmar Jun 01 '18 at 02:05
  • @CertainPerformance yea I know. The current codebase and what we are trying to accomplish is forcing us to do this. A refactor would allow us to take a different path but as of now management says a refactor would take too much time. – Jeff Jun 01 '18 at 02:28
  • @mentallurg we've tried using jquery `serializeArray()`, then we tried to transform the object but we still end up with keys that contain brackets and are hard to parse and manipulate. It becomes even harder the more complex the data structure is. – Jeff Jun 01 '18 at 02:30

0 Answers0