I want to make a function called createAssociativeArray which will recive two parameters: string and object, like this:
function createAssociativeArray(string, object) { //... } The last item of string should get the object data. See an use/return example:
createAssociativeArray('key1.key2.key3', { data1: 1, data2: 2, data3: 3 }); // key1: { // key2: { // key3: { // data1: 1, // data2: 2, // data3: 3 // } // } // } What's the most simple and robust method to do it?
Use eval isn't is a possibility.
What I was tried:
function createAssociativeArray(string, object) { string = string.split('.'); return string.reduce(function(_object, _target, i) { _object[_target] = (i + 1 === string.length ? object : {}); return _object; }, {}); } It didn't produced the expected result because the object is reseted to {}.
[JSFiddle]
ivariable come from?indexfromreduce(updated).