I actually wish to convert a string to a deep object, but am pretty sure converting the string to an array is the first step. Let me explain.
I am using xeditable which by default will send {"name": "somePropertyName", "value": "someValue"} to the server, however, I wish to send {"somePropertyName": "someValue"}. I am able to accomplish this by setting $.fn.editable.defaults.params to the appropriate callback.
Now the part I am stuck on. I am using a special naming pattern that if the name has periods in it (i.e. name is a.b.c), I don't want to send {"a.b.c": "someValue"} to the server, but instead send {"a":{"b":{"c":"someValue"}}} to the server.
I've got a partially working version, however, it is not very elegant and more importantly I haven't gotten the last property working and have temporarily hardcoded it which is not acceptable.
How can this be accomplished?
$.fn.editable.defaults.params = function(params){
return nvp2obj(params.name, params.value);
}
function nvp2obj(n, v, d) {
d = d ? d : '.';
n = n.split('.');
var o = {};
var r = o;
n.reduce(function(total, currentValue, currentIndex, arr) {
if(r) {
r[currentValue]={};
r=o[currentValue];
}
else {
//this is obviously not correct
o.a.b.c=v;
}
return o;
}, o);
return o;
}
var test = nvp2obj('a.b.c', 'someValue'); //{"a":{"b":{"c":"someValue"}}}
console.log('test', JSON.stringify(test));