JSFiddle - React, Tailwind, and code Playground
HTML
<label>Below are unique tags (working fine)</label>
<input type="text" data-nest="parent.child.grandchild1" value="gchild1-first"/>
<input type="text" data-nest="parent.child.grandchild2" value="gchild2-second"/>
<label>Below is multiple occurances of the same tag (find a way to break these into an array of objects)</label>
<input type="text" data-nest="parent.child.grandchild" value="gchild-first"/>
<input type="text" data-nest="parent.child.grandchild" value="gchild-second"/>
<label>Single array example</label>
<input type="text" data-nest="parent.child.array" value="this,is,an,array"/>
<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.
debugger;
if (typeof currentObj[lastKey] === 'undefined') {
currentObj[lastKey] = value;
} else if(!Array.isArray(currentObj[lastKey])) {
currentObj[lastKey] = [currentObj[lastKey], value];
} else if(Array.isArray(currentObj[key])){
currentObj[lastKey].push(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);
});
// as a bonus - this is how I went about breaking multiple values within a single input into an array
function traverseObject(object){
// iterate through the object
for (var i in object){
var value = [object[i]];
// if the value contains a comma
...