I have code that loops through a string to make a sort of tree in the form of a JSON Object. Every time a certain character is reached, the array should go down a level. The only way I have been able to accomplish this is with eval(). I recreate the index necessary to go down a row in a custom push function by generating something like this JSON_OBJECT[2][8].push(value). eval() is not only a security issue but is also pretty slow.
Below I have a similar script where I used a space as the certain character. When running 1,000 randomly generated filler words the script takes ~1000ms. By just removing the eval and replacing it with a json.push(value) the script takes at most 3ms.
I know that eval() wasn't using all of the time, but it has to be a big part. Speed is a big factor in the script and a 1,000 words is not very far off from what this script will be processing. Is there a way I can do this without eval()?
Here's the script
var string = 'lorem ipsum dolor sit amet consectetur adipiscing elit ut',
json = [],
levelIndex = [];
for (let i = 0; i < string.length; i++) {
if (string[i - 1] == ' ') {
levelIndex.push(deepestLength() - 1);
}
if (string[i] == ' ') {
customPush([]);
} else {
customPush(string[i]);
}
}
function customPush(value) {
let path = '';
for (let i = 0; i < levelIndex.length; i++) {
path += '[' + levelIndex[i] + ']';
}
eval('json' + path + '.push(' + JSON.stringify(value) + ')');
}
function deepestLength() {
let deepest = json;
for (let i = 0; i < levelIndex.length; i++) deepest = deepest[levelIndex[i]];
return deepest.length;
}
document.write('Completed Array: <br>' + JSON.stringify(json));