繁体   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