我有一个JavaScript对象,看起来像这样.
var myObj = [
{
"HOLIDAY": {
"Sun": "Date","Mon": "Date","Tue": "Date","Wed": "Date","Thr": "Date","Fri": "Date","Sat": "Date"
}
}
]
我有一些HTML代码,看起来像这样
在HTML上,如果我对该字段进行任何更改,我已经存储了要修改的JavaScript变量.我编写了类似这样的JavaScript代码.
$(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());
});
有没有更好的方法来解决这个问题,目前我使用的是eval()我不想使用,因为很多元素都会有’change’事件而show’eval’会影响我的代码的性能.
最佳答案
// Input
var myObj = [{
"HOLIDAY": {
"Sun": "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"));