簡體   English   中英

如何檢查我的密鑰是否存在於對象數組中

[英]How to check whether my key exists in array of object

var arr = [{
   key: "key1", value: "z"
}, {
   key: "key2", value: "u"
}, {
   ...
}];

如何檢查我的key:"key1"是否已經存在。 如果它不存在,我需要在 ma 數組中添加鍵。

if(arr.hasOwnProperty("key1")){
      arr.unshift({key:"key1", value:"z"});
}

為了更容易,你應該這樣存儲你的數據:

var map = {
       "key1": "z",
       "key2": "u"
};

然后你可以做你的檢查,如果你的鍵不與對象上的任何現有屬性沖突,並且你不需要空值,你可以讓它更容易。

if (!map["key1"]) {
   map["key1"] = "z";
}

如果你真的需要完整的對象(你的畢竟只是一個例子),我會將對象存儲為鍵的值,而不僅僅是將對象存儲在數組中。 也就是說,使它成為一個地圖,而不是一個數組。

因為你有一個充滿對象的數組,你需要這樣做:

(ES3)

function lookup( name ) {
    for(var i = 0, len = arr.length; i < len; i++) {
        if( arr[ i ].key === name )
            return true;
    }
    return false;
}

if( !lookup( 'key1' ) ) {
    arr.push({
        key: 'key1',
        value: 'z'
    });
}

如果元素未通過測試,您可以使用 ECMAScript 5 filter方法從數組中刪除元素。 如果生成的數組沒有元素,您就知道沒有元素包含您的值:

if(!arr.filter(function(elem) {
    return elem.key === "key1";
}).length) {
    arr.push({ key: "key1", value: "z" });
}

如果你想讓它在舊瀏覽器中工作,你需要使用墊片來確保Array.prototype.filter被定義。

您可以檢查數組和對象以查看數組鍵或對象屬性是否存在。 它非常有用,並且用於檢查兩種類型的方式相同。

/**
 * Check if an array key or object property exists
 * @key - what value to check for
 * @search - an array or object to check in
 */
function key_exists(key, search) {
    if (!search || (search.constructor !== Array && search.constructor !== Object)) {
        return false;
    }
    for (var i = 0; i < search.length; i++) {
        if (search[i] === key) {
            return true;
        }
    }
    return key in search;
}

用法:

作為數組

key_exists('jared', ['jared', 'williams']); //= true

作為對象

key_exists('jared', {'jared': 'williams'}); //= true 
var key;
for(var i = 0; i < arr.length; i++)
{
    if(arr[i].key == "key1")
    {
        key = arr[i];
        break;
    }
}
if(typeof (key)=='undefined') //for if the value is 0 as int
{
    key = {
        key: "key1", value: "aaa"
    };
    arr.push(key);
}

以下是@jAndy 接受的答案的兩個更明確的版本。

我為自己制作了第一個版本,以便更好地理解邏輯並添加以下內容:

如果鍵確實存在,則增加匹配對象的計數屬性,否則創建一個計數為 1 的新對象。

在第二個版本中,我意識到我更喜歡我的arrayOfObjects變量是一個object ,以便以后我可以專門針對值而不是循環遍歷數組直到我得到匹配,然后獲取相關的對象值。 因此該版本使用對象而不是對象數組。

版本 01 - 對象數組

 // based on: https://stackoverflow.com/a/9177103/1063287 // the original array of objects var arrayofObjects = [{ id: "CY01", count: 1 }, { id: "CY33", count: 5 }, { id: "CY55", count: 8 } ]; // show the array in the interface $(".before").text(JSON.stringify(arrayofObjects)); // define lookup function (must have access to arrayofObjects) function lookup(key_to_check) { // for each object in the array of objects for (var i = 0; i < arrayofObjects.length; i++) { // if the object key matches the key to check if (arrayofObjects[i]["id"] === key_to_check) { // return true with index of matching object var returnObject = {}; returnObject["exists"] = true; returnObject["index"] = i; return returnObject; } } // if the above loop has not already returned a value // return false var returnObject = {}; returnObject["exists"] = false; return returnObject; } // on click, check whether the key exists $(document).on("click", ".run", function() { var key_to_check = $(".key_to_check").val(); $(".checking").text(key_to_check); var returnObject = lookup(key_to_check); // if key to check doesn't exist add it if (returnObject["exists"] === false) { console.log("key doesn't exist, adding object"); arrayofObjects.push({ id: key_to_check, count: 1 }); } else if (returnObject["exists"] === true) { // else if it does exists, increment the relevant counter console.log("key does exist, incrementing object count value"); var index = returnObject.index; arrayofObjects[index].count += 1; } $(".after").text(JSON.stringify(arrayofObjects)); });
 body { font-family: arial; font-size: 14px }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>enter an existing or non-existing key and click run.</p> <p>if existing, increment count, otherwise create new object with count of 1.</p> <input class="key_to_check"><button class="run">run</button> <br><br> <div>array of objects - before: <span class="before"></span> </div> <div>checking:<span class="checking"></span></div> <div>array of objects - after: <span class="after"></span></div>

版本 02 - 一個對象

 // based on: https://stackoverflow.com/a/9177103/1063287 // the original object var myObject = { "CY01": 1, "CY33": 5, "CY55": 8 }; // show the object in the interface $(".before").text(JSON.stringify(myObject)); // define lookup function (must have access to myObject) function lookup(key_to_check) { // for each property in the object for (key in myObject) { // if the key matches the key to check if (key === key_to_check) { // return true return true } } // if the above loop has not already returned a value // return false return false } // on click, check whether the key exists $(document).on("click", ".run", function() { var key_to_check = $(".key_to_check").val(); $(".checking").text(key_to_check); var returnObject = lookup(key_to_check); // if key to check doesn't exist add it if (returnObject === false) { console.log("key doesn't exist, adding object"); myObject[key_to_check] = 1; } else if (returnObject === true) { // else if it does exists, increment the relevant counter console.log("key does exist, incrementing object count value"); myObject[key_to_check] += 1; } $(".after").text(JSON.stringify(myObject)); });
 body { font-family: arial; font-size: 14px }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>enter an existing or non-existing key and click run.</p> <p>if existing, increment count, otherwise create new property with count of 1.</p> <input class="key_to_check"><button class="run">run</button> <br><br> <div>my object - before: <span class="before"></span> </div> <div>checking:<span class="checking"></span></div> <div>my object - after: <span class="after"></span></div>

暫無
暫無

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

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