如何检查我的键是否存在于对象数组中 [英] How to check whether my key exists in array of object

查看:44
本文介绍了如何检查我的键是否存在于对象数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何检查我的 key:"key1" 是否已经存在.如果不存在,则需要在ma数组中添加密钥.

How to check whether my key:"key1" exists already or not. If it does not exist, i need to add the key in ma array.

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

推荐答案

既然您已经用对象填充了一个数组,则需要这样做:

Since you've got an Array filled with Objects, you need to do it like:

(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'
    });
}

这篇关于如何检查我的键是否存在于对象数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆