那这个呢 :
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];
}
}
使用输入对象的示例(可能是使用 $.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);
})
结果
{
"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"
}