Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Update a object value by retrieving variable names from string

I have a JavaScript object which looks like this.

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

and I have some HTML code which looks like this

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

On HTML I have stored which JavaScript variable to modify if I do any change to that field. I have written JavaScript code which look 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 any better approach to this problem, currently I am using eval() which I don't want to use, as many elements will have 'change' event and show 'eval' can effect the performance of my code.

like image 985
dhunmoon Avatar asked Oct 17 '22 16:10

dhunmoon


1 Answers

 // 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"));
like image 76
Akshay Hegde Avatar answered Oct 20 '22 23:10

Akshay Hegde