插入新元素时如何为 JavaScript 对象生成动态 ID?
How to generate dynamic id for JavaScript object when inserting new element?
我里面有 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}];
我必须在那个数组中 insert/update 记录。我不确定检查该数组中是否存在记录的最佳方法是什么。如果存在则更新 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
}
}
您可以使用 Object
来存储您的 Collection of Objects
。每次向集合中注入一个对象时,都会生成一个新的id(根据集合的长度),如果向集合中插入的对象id
已经存在,则只执行一次更新。
const collection = {};
function insert(obj){
// if id is set in object and object is already in Collection...
if(obj.id && collection.hasOwnProperty(obj.id) ){
// Update object!
collection[obj.id]= Object.assign(collection[ obj.id], obj) ;
}else{
// if provided object has no ID... generate it!
if( !obj.id ) obj.id = Object.keys(collection).length;
// insert provided object to collection;
collection[obj.id]= obj;
}
// return generaed id;
return obj.id;
}
// Let's test...
let obj_1 ={"first":"Mike","last":"Johnson","email":"mjohnson@gmail.com","phone":"(203) 567-9055","status":1};
let obj_2 = {"first":"John","last":"Dunn","email":"jdunn@gmail.com","phone":"(319) 451-7889","status":1};
// insert bth object
insert(obj_1);
insert(obj_2);
// perform a change in object 2
obj_2.first ='Joseph';
// insert object 2 again...
insert(obj_2);
// object 2 has been updated, and all have unique ids
console.log(collection);
找到数组中的最后一个对象并获取它的 id:
contacts[contacts.length-1].id
然后简单地加上1
,你就有了下一个身份证号码。
评论中提到了这一点,但我会稍微充实一下。
如果您的数据是键控到 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'])
希望这是尝试这种方法而不是数组的一点动力。
您可以创建一个全局变量并将其用作计数器,每次新记录都可以将其增加一,现有的只需更新。
您可以将所有 json 存储在数据库中,在获取时只需计算数组 elements/last 元素的 ID 并将其设置在计数器中。
此外,如果您不需要按顺序自动生成 ID,您也可以使用随机函数每次生成唯一的 ID。
如果您将数据作为对象的对象来管理,您可以通过简单的方式实现这一点。
var contacts = {
1: {
first: "Mike",
last: "Johnson",
email:"mjohnson@gmail.com",
phone:"(203) 567-9055",
status:"1"
},
2: {
first: "John",
last: "Dunn",
email:"jdunn@gmail.com",
phone:"(319) 451-7889",
status:"1"
},
3: {
first: "Lisa",
last: "Morgan",
email:"lmorgan@gmail.com",
phone:"(508) 233-8908",
status:"1"
},
4: {
first: "Dave",
last: "Hart",
email:"dhart@gmail.com",
phone:"(509) 874-9411",
status:"1"
}
};
var frmKey = 5;
if(contacts[frmKey]){
console.log(contacts[frmKey]);
// If already exist in array then update object
}else{
contacts[frmKey] = {first: "Lisa1",last: "Morgan1", email:"lmorgan1@gmail.com", phone:"(508) 233-8908", status:"1" };
console.log("Added New Key::"+frmKey,contacts[frmKey]);
}
我里面有 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}];
我必须在那个数组中 insert/update 记录。我不确定检查该数组中是否存在记录的最佳方法是什么。如果存在则更新 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
}
}
您可以使用 Object
来存储您的 Collection of Objects
。每次向集合中注入一个对象时,都会生成一个新的id(根据集合的长度),如果向集合中插入的对象id
已经存在,则只执行一次更新。
const collection = {};
function insert(obj){
// if id is set in object and object is already in Collection...
if(obj.id && collection.hasOwnProperty(obj.id) ){
// Update object!
collection[obj.id]= Object.assign(collection[ obj.id], obj) ;
}else{
// if provided object has no ID... generate it!
if( !obj.id ) obj.id = Object.keys(collection).length;
// insert provided object to collection;
collection[obj.id]= obj;
}
// return generaed id;
return obj.id;
}
// Let's test...
let obj_1 ={"first":"Mike","last":"Johnson","email":"mjohnson@gmail.com","phone":"(203) 567-9055","status":1};
let obj_2 = {"first":"John","last":"Dunn","email":"jdunn@gmail.com","phone":"(319) 451-7889","status":1};
// insert bth object
insert(obj_1);
insert(obj_2);
// perform a change in object 2
obj_2.first ='Joseph';
// insert object 2 again...
insert(obj_2);
// object 2 has been updated, and all have unique ids
console.log(collection);
找到数组中的最后一个对象并获取它的 id:
contacts[contacts.length-1].id
然后简单地加上1
,你就有了下一个身份证号码。
评论中提到了这一点,但我会稍微充实一下。
如果您的数据是键控到 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'])
希望这是尝试这种方法而不是数组的一点动力。
您可以创建一个全局变量并将其用作计数器,每次新记录都可以将其增加一,现有的只需更新。
您可以将所有 json 存储在数据库中,在获取时只需计算数组 elements/last 元素的 ID 并将其设置在计数器中。
此外,如果您不需要按顺序自动生成 ID,您也可以使用随机函数每次生成唯一的 ID。
如果您将数据作为对象的对象来管理,您可以通过简单的方式实现这一点。
var contacts = {
1: {
first: "Mike",
last: "Johnson",
email:"mjohnson@gmail.com",
phone:"(203) 567-9055",
status:"1"
},
2: {
first: "John",
last: "Dunn",
email:"jdunn@gmail.com",
phone:"(319) 451-7889",
status:"1"
},
3: {
first: "Lisa",
last: "Morgan",
email:"lmorgan@gmail.com",
phone:"(508) 233-8908",
status:"1"
},
4: {
first: "Dave",
last: "Hart",
email:"dhart@gmail.com",
phone:"(509) 874-9411",
status:"1"
}
};
var frmKey = 5;
if(contacts[frmKey]){
console.log(contacts[frmKey]);
// If already exist in array then update object
}else{
contacts[frmKey] = {first: "Lisa1",last: "Morgan1", email:"lmorgan1@gmail.com", phone:"(508) 233-8908", status:"1" };
console.log("Added New Key::"+frmKey,contacts[frmKey]);
}