我有一个数组,每个数组里面都是一周的每一天的json对象,所以我的数组看起来像这样:
var array = [
{
"wednesday":{
"notes":"some notes for Wednesday"
},
},
{
"thursday":{
"notes":"some notes for Thursday"
}
}
];
我可以通过调用以下内容直接更新我的对象:
array[0].wednesday.notes = "updating Wednesday notes";
但是,我需要动态更新它....
我有一个看起来像这样的函数,我需要在我的json对象上动态调用星期几而不是在周三被锁定,我需要能够在周三,星期四,星期五等我的电话上调用对象,我该怎么做?
function updateObject(index, empNum) {
console.log(index+", "+empNum)
array[index].employee = $("#employee_" + empNum).val();
array[index].wednesday.notes = $("#employee_" + empNum + "_wed_notes").val();
array[index].wednesday.start = $("#employee_" + empNum + "_wed_shift_start").val();
array[index].wednesday.lunch = $("#employee_" + empNum + "_wed_lunch").val();
array[index].wednesday.end = $("#employee_" + empNum + "_wed_shift_end").val();
array[index].wednesday.short_day = $("#employee_" + empNum + "_wed_short_day").is(':checked');
array[index].wednesday.lack_of_work = $("#employee_" + empNum + "_wed_lack_of_work").is(':checked');
array[index].wednesday.full_day = $("#employee_" + empNum + "_wed_full_day").is(':checked');
var row_count = $("input[id*='employee_" + empNum + "_wed_job_']").length;
for (var i = 0; i < row_count; i++) {
var data = {};
data.job = $("input[id*='employee_" + empNum + "_wed_job_']").eq(i).val();
data.hrs = $("input[id*='employee_" + empNum + "_wed_hrs_']").eq(i).val();
data.cost_code = $("input[id*='employee_" + empNum + "_wed_cost_code_']").eq(i).val();
data.st = $("input[id*='employee_" + empNum + "_wed_st_']").eq(i).is(':checked');
data.ot = $("input[id*='employee_" + empNum + "_wed_ot_']").eq(i).is(':checked');
data.dt = $("input[id*='employee_" + empNum + "_wed_dt_']").eq(i).is(':checked');
array[index].wednesday.data[i] = data;
}
}
我试过像做的那样
array [index]。[thursday] .notes =“x”;
但不幸的是,这不起作用,我需要能够在调用函数时调用我需要的那一天
所以我需要它像updateObject(2,1,"thursday");
答案 0 :(得分:1)
您只需使用bracket notation访问数组/对象中的正确元素。
此功能可让您输入周数(数组索引)以及您想要更新的日期。
var array = [
{
"wednesday":{
"notes":"some notes for Wednesday"
},
},
{
"thursday":{
"notes":"some notes for Thursday"
}
}
];
function updateArray(index, day, newNotes) {
array[index][day].notes = newNotes;
}
console.log('before', array);
updateArray(1, 'thursday', 'updated notes');
console.log('after', array);
答案 1 :(得分:0)
您可以这样访问所有数据:
updateObject(0, "15 employees")
该函数隔离在某个位置给出的密钥并访问它。
示例:const updateObject = (day, empNum) => {
const i = array.map(r => {
const k = Object.keys(r)[0];if (!k) {return false}
return r[k]
}).filter(r => r)[0]
if (!i) {return console.error("Invalid Day [%s] provided",day)}
i.notes = `Whatever you want with ${empNum}`
}
如果您希望白天做^^,那么您的功能将如下所示:
updateObject('tuesday', "15 employees")
不是你可以像{{1}}
那样使用它