我里面有 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
}
}
最佳答案
这在评论中提到过,但我会稍微充实一下。
如果您的数据是一个以 ID 而不是数组为键的对象,它将强制 ID 是唯一的,因为对象必须具有唯一的键。
例如:
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}];
// just a quick dirty conversion
let obj = contacts.reduce((a, c) => (a[c.id] = c, a), {})
//Object looks like:
console.log(obj)
// find the largest key // maybe a good way to decide the next key
largest_id = Math.max(...Object.keys(obj))
console.log("largest ID", largest_id)
// is ID 4 taken?
console.log("is there a 4", 4 in obj) //yes
// alternatively obj.hasOwnProperty('4')
// is 5?
console.log("is there a 5", 5 in obj) //no
// update ID 4:
obj['4'].first = "Mark"
console.log(obj['4'])
希望这是尝试这种方法而不是数组的一点动力。
关于javascript - 插入新元素时如何为 JavaScript 对象生成动态 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51644406/