如何检查我的键是否存在于对象数组中
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"
};
然后,您可以进行检查,如果您的键与对象上的任何现有属性不冲突,并且您不需要 null 值,则可以使其更容易。
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
。
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);
}
您可以使用此检查数组和对象以查看数组键或对象属性是否存在。它非常有用,并且以相同的方式用于检查这两种类型。
/**
* 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
以下是@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>
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在Javascript中转换对象数组
- 在JavaScript中通过索引从对象数组中获取值
- Backbone虹吸以获取对象数组
- 如何在DataTables 2.1中迭代对象数组
- Javascript-根据赋值顺序,按键合并对象数组
- 将事件附加到对象/数组
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- javascript在数组中获取对象数组中键的所有不同值
- 在对象数组中查找多个值的d3范围
- Undercore.js获取对象数组中键对象的值
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- 如何通过json对象数组为嵌套对象赋值
- 如何检查id(在id列表中)是否存在于具有id的对象数组中
- Javascript Array.indexOf() 在应用于对象数组时表现出奇怪的行为
- 如何检查我的键是否存在于对象数组中
- 检查key是否存在于对象数组中
- 相当于SQL与Javascript对象数组的完全连接
- 没有数.相对于对象数组中的另一个属性的唯一属性的出现