簡體   English   中英

比較JavaScript中數組中的對象ID

[英]Compare Object Ids from Array in JavaScript

我有一些對象的數組。 每個對象都有一個id 因此,當生成一個新的id ,我想檢查具有該id的對象是否已經存在。 如果存在相等的id ,則應生成一個新的id

generateId() {
    var records = store.getRecords(); // get all the objects
    var newId = getNewId(); // calculate a new id

    if (record.id == newId) // id already exists // record.id = id of the object
        newId = generateId(); // generate a new id
    else
        return newId; // return the id
}

getNewId() {
  // generate Id...
}

那么, if (record.id == newId)我如何在這里檢查我的所有記錄? 我使用JQuery。

您可以使用簡單的for循環來簡化操作,如果您獲得了很多記錄,則可能效率不高。 如果所有記錄的對象結構都相同,並且假定對象值的數據類型與newId變量匹配,則此函數將達到目的。

function DoesExist() {
   for(var i = 0; i < records.length; i++) {
     if(records[i].id == newId)
        return true;
   }

   return false;
}

我要解決的方法是將邏輯拆分為多個函數,以便可以對照現有id檢查任何新id 然后,將其包裝在循環中,我可以檢查生成的值,直到找到不在數組中的值為止。 例如(為測試添加的方法和值):

 function generateId() { var records = store.getRecords(); // get all the objects var newId; var isUnique = false; while (!isUnique) { // check if unique, repeatedly newId = getNewId(); // calculate a new id isUnique = checkId(newId); } return newId; // return the id (is unique) } // Check if the id is unique against existing records function checkId(newId) { var records = store.getRecords(); for (var key in records) if (records[key].id == newId) return false; return true; } // Added for testing function getNewId() { return Math.round(Math.random() * 10); } var store = {getRecords: function() {return [{id: 1}, {id: 2}, {id: 4}, {id: 6}];}} // Actual testing console.log(generateId()); 

這應該作為增量ID生成器工作:

 const data = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}]; const exists = id => data.some(o => o.id === id); const newId = (start = 0) => { const id = ++start; return exists(id) ? newId(id) : id; }; // you can also evaluate to implement some uid logic... // there isn't much you can do on the client, but, // this could also help const newUID = () => { const uid = Math.random().toString(32).substr(2); return exists(uid) ? newUID() : uid; } console.log({ incrementalID: newId(), UID: newUID() }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM