Search code examples
javascriptjqueryarraysgenerate

How to generate dynamic id for JavaScript object when inserting new element?


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 
        }
}

Solution

  • This was mentioned in a comment, but I'll flesh it out a bit.

    If your data is an object keyed to ID instead of an array, it will force IDs to be unique, since objects must have unique keys.

    For 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}];
    
    // 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'])

    Hopefully that is a little bit of an incentive to try this approach instead of an array.