如何检查我的密钥是否存在于数组对象中

时间:2012-02-07 13:21:45

标签: javascript

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

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

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

6 个答案:

答案 0 :(得分:19)

为了方便您存储数据:

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

然后你可以进行检查,如果你的密钥与对象上的任何现有属性都没有冲突,并且你不需要空值,你可以更容易。

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

如果你真的需要完整的对象(你的实际上只是一个例子),我会将对象存储为键的值,而不仅仅是将对象存储在数组中。也就是说,将它设为地图,而不是数组。

答案 1 :(得分:10)

由于你有一个填充了Objects的数组,你需要这样做:

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

答案 2 :(得分:5)

如果没有通过测试,您可以使用ECMAScript 5 filter方法从数组中删除元素。如果生成的数组没有元素,则表示没有任何元素:

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

如果您希望它在旧版浏览器中运行,您需要使用填充程序来确保定义Array.prototype.filter

答案 3 :(得分:1)

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

答案 4 :(得分:1)

您可以检查数组和对象,以查看是否存在数组键或对象属性。它非常有用,它用于检查两种类型。

/**
 * 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 

答案 5 :(得分:0)

以下是@ jAndy接受的答案的两个更明确的版本。

我为自己制作了第一个版本,因此我可以更好地理解逻辑并添加以下内容:

  

如果密钥确实存在,则递增匹配的count属性   对象,否则创建一个计数为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>