jQuery update object in array when found?

Viewed 113

I have an array of objects. I have this code that finds an object in array. My question is when the object is found, how do I update it?

$(document).on("change", "input[name=ActualFinish]", function () {

        var job = $(this).parent().parent().find('input[name=Job_No]').val();
        var actualFinish = $(this).parent().parent().find('input[name=ActualFinish]').val();
        var task = $(this).parent().parent().find('input[name=LibrayTaskID]').val();

        if (updatingData.find(x => x.Job == job && x.TaskID == task)) {

            console.log("found. How do I update Date1?");

        }
        else {

            updatingData.push({ Job: job, TaskID: task, Date1: actualFinish });

        }

        console.log(updatingData);

    });
1 Answers

I Think there is no need to update anything if you're finding record on matching attributes.

However if you want to update existing record, you can use findIndex method to find index of that matched record and then update the value of object at that index as below:

...
var matched_index = updatingData.findIndex(x => x.Job == job && x.TaskID);

//findIndex method returns index on matching and -1 if not match.

if ( matched_index !== -1)) {

        // Update record here with matched_index
        updatingData[matched_index].job = // whatever
        updatingData[matched_index].actualFinish = // whatever
        updatingData[matched_index].task = // whatever

        console.log("Record is updated");

    }
    else {

        updatingData.push({ Job: job, TaskID: task, Date1: actualFinish });

    }
...
Related