0

我里面有 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 
        }
}
4

5 回答 5

2

评论中提到了这一点,但我会稍微充实一下。

如果您的数据是键控到 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'])

希望这是尝试这种方法而不是数组的动力。

于 2018-08-02T02:04:43.900 回答
1

找到数组中的最后一个对象并获取它的 id:

contacts[contacts.length-1].id

然后只需添加1,您就有下一个 ID 号。

于 2018-08-02T02:00:22.453 回答
0

如果您将数据作为对象的对象进行管理,则可以通过简单的方式实现这一点。

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

}

于 2018-08-02T02:21:51.877 回答
0

您可以创建一个全局变量并将其用作计数器,每次新记录都可以将其增加一,对于现有的只是更新。

您可以将所有 json 存储在数据库中,在获取时只需计算数组元素/最后一个元素的 Id 并将其设置在计数器中。

此外,如果您不需要按顺序自动生成的 id,您也可以使用随机函数每次生成唯一的 id。

于 2018-08-02T02:10:06.837 回答
0

您可以使用 anObject来存储您的Collection of Objects. 每次在集合中注入对象时,都会生成一个新的 id(基于集合的长度),如果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);

于 2018-08-02T01:55:37.523 回答