This is a reverse question to this question.
Given an object x={a:1,b:2}
and a string c.d=3
, modify object x to the following:
What about this :
function setObj (str, value, obj) {
var ref = obj, keys = str.split('.');
while (keys.length) {
var currentKey = keys.shift();
ref[currentKey] = keys.length ? (ref[currentKey] ? ref[currentKey] : {}) : value;
ref = ref[currentKey];
}
}
Example with an input object using (could be some form values extracted with $.serializeArray)
var serializedInputs = [
{name: 'fruits[1][name]', value: 'Banana'},
{name: 'fruits[1][id]', value: '1'},
{name: 'fruits[2][name]', value: 'Strawberry'},
{name: 'fruits[2][id]', value: '2'},
{name: 'fruits[3][name]', value: 'Raspberry'},
{name: 'fruits[3][id]', value: '3'},
{name: 'fruits[4][name]', value: 'Kiwi'},
{name: 'fruits[4][id]', value: '4'},
{name: 'fruits[5][name]', value: 'Mango'},
{name: 'fruits[5][id]', value: '5'},
{name: 'selected_fruit_id', value: '1'},
]
// This variable holds the result
var obj = {}
serializedInputs.forEach(function(item) {
// Turning square brackets into dot notation
setObj(item.name.replace(/\]/g, '').replace(/\[/g, '.'), item.value, obj);
})
Result
{
"fruits": {
"1": {
"name": "Banana",
"id": "1"
},
"2": {
"name": "Strawberry",
"id": "2"
},
"3": {
"name": "Raspberry",
"id": "3"
},
"4": {
"name": "Kiwi",
"id": "4"
},
"5": {
"name": "Mango",
"id": "5"
}
},
"selected_fruit_id": "1"
}