我里面有 JavaScript 对象元素的数组。这是示例:
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}];
我必须在该数组中插入/更新记录。我不确定检查该数组中是否存在记录的最佳方法是什么。如果存在则更新 js 对象,如果不存在则生成新的id
. 理想情况下,该 id 将是一个整数,并在 js 对象中的最高当前 id 之后开始。所以在数据上面的最高 id 值是4
. 如果我插入新记录id
,新记录应该是5
. 有没有用 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
}
}