JSFiddle - React, Tailwind, and code Playground
HTML
<label>Multiple occurances of the same tag</label>
<input type="text" data-nest="parent.child.grandchild" value="first"/>
<input type="text" data-nest="parent.child.grandchildFriend" value="firstFriend"/>
<input type="text" data-nest="parent.child.grandchild" value="second"/>
<input type="text" data-nest="parent.child.grandchildFriend" value="secondFriend"/>
<div id="test">
Test
</div>
CSS
#test{
padding: 5px;
border: 1px solid black;
font-size: 15px;
cursor: pointer;
width: 150px;
margin: 5px;
text-align: center;
}
input{
display: block;
margin: 5px;
padding: 5px;
width: 150px;
}
JavaScript
var json = {};
config = {
set: function(keyValueString) {
var pair = keyValueString.split('=');
// left of the = is the key path
var keyPath = pair[0];
// right of the = is the value to set
var value = pair[1];
// split keyPath into an array of keys
var keys = keyPath.split('.');
var key;
var currentObj = json;
// loop through all keys in the key path, except the last one.
// this creates the object structure implied by the key path.
// we want to do something different on the last iteration.
for (var i=0; i < keys.length-1; i++) {
// Get the current key we are looping
key = keys[i];
// if the requested level on the current object doesn't exist,
// make a blank object.
if (typeof currentObj[key] === 'undefined') {
currentObj[key] = {};
}
currentObj = currentObj[key];
}
// our loop doesn't handle the last key, because that's when we
// want to set the actual value.
var lastKey = keys[keys.length-1]
// set the property of the deepest object to the value.
currentObj[lastKey] = value;
}
};
// iterate through all of our inputs, and nest them based off their data-* attribute
$('input').each(function(){
// set nest = value setup, e.g. parent.child.grandchild = first
// we then break this
var key = $(this).attr('data-nest') + '=' + $(this).val();
config.set(key);
});
$('#test').on('click', function(){
console.log(json)
});