Hello,
Recently, I had a problem with making some structure for storing a drag’n’drop state of an element. The best way that came to my mind was making a mixtype structure of arrays and objects. For example, I had an array with the following structure:
{ "docs": [ { "minimize": false, "docs": [ { "minimize": true } ] }, { "minimize": false, "docs": [ { "minimize": true } ] } ] }
So, I needed to get the last nested element of that object by the path like — docs_0_docs_0 . And also, after getting the nested element, I needed to set the value back to the element. The function with the implementation of setting data is below:
function set_data_to_object(object, path, data, type = 'object') { const isNumeric = (string) => /^[+-]?\d+(\.\d+)?$/.test(string) if (typeof (path) == 'string') { path = path.split('_'); } if (typeof (object) !== 'object' || Object.keys(object).length == 0) { object = type === 'object' ? {} : []; } const element = path[0]; if (path.length == 1) { object[element] = data; } else { if (isNumeric(element)) { object[element] = set_data_to_object(object[element], path.slice(1), data, 'object'); } else { object[element] = set_data_to_object(object[element], path.slice(1), data, 'array'); } } return object; }
The first argument of the function is an object. The object can be empty empty like — {}; in this case the parent elements will be made corresponding to the path.
The second argument is the path, as I mentioned above it should be like — docs_0_docs_0 . Where the underscore symbol is delimiter symbol.
The third argument is the data that you want to the object.
And finally, the function will return the changed object with the set data.
For getting data from the object, I wrote another function:
function get_data_from_object(object, path) { if (typeof (path) == 'string') { path = path.split('_'); } const element = path[0]; if (path.length == 1) { return object[element]; } else { return get_data_from_object(object[element], path.slice(1)); } }
The first argument of the function is the object that contains the structure like I described above.
The second argument is the path like — docs_0_docs_0.
I hope, it can be helpful for somebody.