I have array of JavaScript object elements inside. Here is example:
var contacts =[{"id":1,"first":"Mike","last":"Johnson","email":"mjohnson@gmail.com","phone":"(203) 567-9055","status":1},{"id":2,"first":"John","last":"Dunn","email":"jdunn@gmail.com","phone":"(319) 451-7889","status":1},{"id":3,"first":"Lisa","last":"Morgan","email":"lmorgan@gmail.com","phone":"(508) 233-8908","status":1},{"id":4,"first":"Dave","last":"Hart","email":"dhart@gmail.com","phone":"(509) 874-9411","status":1}];
I have to insert/update records in that array. I'm not sure what would be the best approach to check if record exist in that array. If exist then update js object, if not generate new id
. Ideally that id would be an integer and starts after the highest current id in js object. So in data above the highest id value is 4
. If I insert new record id
for the new record should be 5
. Is there a good way to achieve that with JavaScript?
function saveContact(){
var frmObject = $(this),
frmKey = $("#frm_id").val(),
formData = frmObject.serialize(),
contactRecord = contacts.find(item => item.id === Number(frmKey));;
if (contactRecord) {
contacts[frmKey] = getJSON(frmObject.serializeArray()); // If already exist in array then update object
}else{
frmKey = 'generate new id';
contacts[frmKey] = getJSON(frmObject.serializeArray()); // If doesn't exist generate new key and insert object in array
}
}