JavaScript: updating the value of an object by extracting variable names from a string

I have a JavaScript object that looks like this.

var myObj = [ { "HOLIDAY": { "Sun": "Date", "Mon": "Date", "Tue": "Date", "Wed": "Date", "Thr": "Date", "Fri": "Date", "Sat": "Date" } } ] 

and I have HTML code that looks like this

  <input data-event="change" data-variable="myObj" data-bind="[0]['HOLIDAY']['Sun']" type="text"> 

In HTML, I saved a JavaScript variable to change if I make changes to this field. I wrote JavaScript code that looks like this.

 $(document).on('change', '[data-event= change]', function(){ //get-variable-name where to bind data //Get object location inside the variable var sVarName = $(this).data('variable'); var sObjLoca = $(this).data('bind'); eval(sVarName+sObjLoca +' = ' $(this).val()); }); 

Is there a better approach to this problem, I am currently using eval() , which I do not want to use, since many elements will have a "change" event and show "eval", can affect the performance of my code.

+5
source share
1 answer

  // Input var myObj = [{ "HOLIDAY": { "Sun": "Date", "Mon": "Date", "Tue": "Date", "Wed": "Date", "Thr": "Date", "Fri": "Date", "Sat": "Date" } }] // Function function updateObject(object, newValue, path) { var stack = path.replace(/\]\[/g, '.').replace(/['"\[\]]/g, '').split('.'); while (stack.length > 1) { object = object[stack.shift()]; } object[stack.shift()] = newValue; return object; } // Output console.log(updateObject(myObj, 'test1', "[0]['HOLIDAY']['Sat']")); console.log(updateObject(myObj, 'test2', "[0]['HOLIDAY']['Tue']")); // Can also set like below console.log(updateObject(myObj, 'otherway', "0.HOLIDAY.Wed")); 
+3
source

Source: https://habr.com/ru/post/1264606/


All Articles