[英]How to check if value exists in array using javascript
我有一個數組形式:
"localValues" : [
{
"localValId" : "8KfbEozjdQYAefuHF",
"localProductCode" : "291105300",
"localMarkupVal" : "2.8",
"localMembersPrice" : "3344"
},
{
"localValId" : "qdCY6Kkvc7e8m4yxw",
"localProductCode" : "291105300234",
"localMarkupVal" : "2.8432",
"localMembersPrice" : "3344333"
},
{
"localValId" : "i827Eve8zBexRSTSP",
"localProductCode" : "291105300",
"localMarkupVal" : "2.8432",
"localMembersPrice" : "899"
}
我正在嘗試返回localProductCode的位置:
var a = localValues;
var location = a.indexOf('291105300');
console.log('location: ' + location)
但是,這將返回-2,這是不正確的,因為該代碼確實存在於數組中。 有人可以幫忙嗎? 先感謝您!
該數組不包含'291105300'
。
除了直接搜索String之外,您還需要找到一個具有給定鍵值的對象:
function hasMatch(array, key, value) {
var matches = array.filter(function(element) {
return element[key] === value;
});
return (matches.length > 0);
}
hasMatch(localValues, 'localProductCode', '291105300') // true
console.log(JSON.stringify(localValues).indexOf('291105300') != -1 ? true : false);
以下代碼將找到您要查找的值的索引。 如果該值不在數組中,則將返回-1。 摘自此SO帖子 。 我只是在最后添加了警報。
var myArray = [0,1,2]
可能會變成var myArray = localValues;
在這種情況下,您可以將needle
設置為所需的值。
var indexOf = function(needle) { if(typeof Array.prototype.indexOf === 'function') { indexOf = Array.prototype.indexOf; } else { indexOf = function(needle) { var i = -1, index = -1; for(i = 0; i < this.length; i++) { if(this[i] === needle) { index = i; break; } } return index; }; } return indexOf.call(this, needle); }; var myArray = localValues, needle = 3, index = indexOf.call(myArray, needle); // 1 alert(index);
編輯:注意到有些晚,您可能正在數組中尋找KEY。
function GetObjectKeyIndex(obj, keyToFind) { var i = 0, key; for (key in obj) { if (key == keyToFind) { return i; } i++; } return null; } // Now just call the following GetObjectKeyIndex(localValues, "localProductCode");
上面的代碼段返回一個ID(如果存在);如果找不到具有該名稱的鍵,則返回null
。
要返回找到該值的所有索引的數組,可以使用map
和filter
:
function findValue(data, key, value) {
return data.map(function (el, i) {
return el[key] === value
}).map(function (el, i) {
return el === true ? i : null
}).filter(function (el) {
return el !== null;
});
}
findValue(data.localValues, 'localProductCode', '291105300'); // [0, 2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.