Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

jQuery update object in array when found?

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);

    });
question from:https://stackoverflow.com/questions/65907679/jquery-update-object-in-array-when-found

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 });

    }
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...