Home > Software engineering >  How to override object property value by index?
How to override object property value by index?

Time:10-16

I have created an object that contains properties with empty values. I would like to access these properties by index and override their values. How can I do this ?

GetAllData: function(){
    var jobPayments = $("#table1 tbody tr");
    var jobPaymentsModels = [];
    jobPayments.each(function (idx, vl) {
        var jobPayment = {date:"",amount:0.0,method:"", reference:""};
        $(this).find("td input,select").each(function (idx, vl) {
            jobPayment[idx] = vl.value;
        });
        jobPaymentsModels.push(jobPayment);
    });
    return jobPaymentsModels;
}

CodePudding user response:

Although object properties do have order now (which you'd need to use an "index" to access them), it's almost never a good idea to use that order, not least because its a bit complicated and depends on how the object is created.

Instead, I'd suggest having the name of the relevant object property on the input/select (if you don't already). Then you can use that name to set the property. Here I'm assuming you have name="date" etc. on the input/select elements:

var jobPayment = {date: "", amount: 0.0, method: "", reference: ""};
$(this).find("td input, select").each(function (idx, vl) {
    const value = vl.name === "amount" ? parseFloat(vl.value) : vl.value;
    jobPayment[vl.name] = vl.value;
});

Details on that jobPayment[vl.name] notation in this question's answers.

  • Related