I have a form with dynamic fields. I want to format some serialized data before submit. I need to reproduce the PHP $$var in Javascript.
Here is the idea in PHP :
I have this :
$data = array('field1', 0, 'key');
$val = 'somevalue';
And I want this :
$field1[0]['key'] = 'somevalue';
So, here is how I would proceed if I were in PHP (I'm not sure if it would work) :
$data = array('field1', 0, 'key');
$val = 'somevalue';
$field1 = array();
$f = $data[0]; # 'field1'
$i = $data[1]; # 0
$k = $data[2]; # 'key'
$$f[$i][$k] = $val; # $field1[0]['key'] = 'somevalue';
I saw that we can use window[var]
in JS but I don't manage to make it work, I tried this :
var val = 'somevalue';
var field1 = [];
var f = data[0];
var i = data[1];
var k = data[2];
window[f][i] = {}; # field1[0] must be an object
window[f][i][k] = val; # field1[0] = {'key': 'somevalue'}
As you can see, it's not very simple. Besides, this code is within a foreach because I don't have only one field but a lot of (field2, field3...).
At the end, I have something like :
var result = {
field1: field1,
field2: field2,
...
field10: field10
}
// console.log(result);
{
field1: [
0 : Object { key: 'somevalue', key2: 'othervalue' }
...
5 : Object { key: 'somevalue2', key2: 'othervalue2' }
]
field2: [...]
...
}
EDIT:
Thanks to the answer of @Nina Scholz:
function formatData(object, keys, value) {
var last = keys.pop();
keys.reduce((o, k, i, a) =>
o[k] = o[k] || (isFinite(i + 1 in a ? a[i + 1] : last) ? [] : {}),
object
)[last] = value;
return object;
}
var data = form.serializeArray();
var result = {};
$(data).each(function(i) {
name = data[i].name; // field name. Ex: "field1[0][key]"
value = data[i].value; // field value
// Format: "field1[0][key]" => array("field1", "0", "key")
array = name.split('[');
array[1] = array[1].replace(']', '');
array[2] = array[2].replace(']', '');
// Format every array of data in a big object "result"
formatData(result, array, value);
});
// JSON encoding of "result" in a hidden field for post-treatment
$('input[name=data]').val(JSON.stringify(result));