I have written a different solution, using recursion. I was using this to namespace the name attribute of input elements. Take, for example, the following:
<input type="number" name="testGroup.person.age" />
And let's say we set the value of that input to "25". We also have an object in our code somewhere:
var data = {
testGroup: {
person: {
name: null,
age: null,
salary: null
}
}
};
So the goal here is to automatically put the value in our input element into the correct position in that data structure.
I've written this little function to create a nested object based on whatever array of namespaces you pass to it:
var buildObject = function ( obj, namespaceArray, pos ) {
var output = {};
output[namespaceArray[pos]] = obj;
if ( pos > 0 ) {
output = buildObject(output, namespaceArray, pos-1);
}
return output;
};
How does it work? It starts at the end of the namespaceArray
array, and creates an object with one property, the name of which is whatever is in the last slot in namespaceArray
, and the value of which is obj
. It then recurses, wrapping that object in additional objects until it runs out of names in namespaceArray
. pos
is the length of the namespaceArray
array. You could just work it out in the first function call, something like if ( typeof(pos) === "undefined" ) pos = namespaceArray.length - 1
, but then you'd have an extra statement to evaluate every time the function recursed.
First, we split the name
attribute of the input
into an array around the namespace separators and get the value of the input:
var namespaceArray = inputElement.name.split("."),
obj = inputElement.value;
// Usually you'll want to do some undefined checks and whatnot as well
Then we just call our function and assign the result to some variable:
var myObj = buildObject(obj, namespaceArray, namespaceArray.length - 1);
myObj will now look like this:
{
testGroup: {
person: {
age: 25
}
}
}
At this point I use jQuery's extend function to merge that structure back into the original data object:
data = $.extend(true, data, myObj);
However, merging two objects is not very difficult to do in framework-free JavaScript and there is plenty of existing code that gets the job done well.
I'm sure there are more efficient ways to get this done, but this method meets my needs well.