5

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
dhunmoon
  • 71
  • 8
  • 1
    first you have 2 data attributes named the same – madalinivascu Feb 23 '17 at 05:53
  • chang? should that be change? `[data-bind = onchange]` ... should that be `[data-bind=onChange]` ? so much wrongness – Jaromanda X Feb 23 '17 at 05:55
  • 1
    First `.on('chang',` should be `.on('change',`. Second, *Is there any better approach*, if the question is about improvements/optimisations, please post it on CodeReviews – Rajesh Feb 23 '17 at 05:55
  • You can avoid using `eval()` to update a variable based on its name if you use a single object with properties instead of multiple variables. So, `masterObj[name] = ...` instead of `eval(name+' = '+ ...)` – nnnnnn Feb 23 '17 at 06:02
  • Sry for mistakes in sample code,it's just question and it's clear what actually what I am asking for. – dhunmoon Feb 23 '17 at 07:14

1 Answers1

3

 // 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"));
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36