2012-02-07 74 views

回答

7

既然你已經有了充滿對象的數組,你需要做的是這樣的:

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

爲了更方便您應該正是如此存儲你的數據:

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

然後,你可以做你檢查,如果你的鑰匙不與對象的任何現有屬性衝突而你不知道t需要空值,你可以更容易。

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

如果你真的需要完整的對象(你畢竟只是一個例子),我會存儲對象爲重點的價值,而不僅僅是對象儲存在數組中。也就是說,使它成爲一張地圖,而不是一個數組。

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

你可以使用的ECMAScript 5 filter方法刪除元素如果他們沒有通過你的測試,從陣列。如果得到的數組沒有任何元素,你知道,有沒有與你的價值:

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

如果你想讓它工作在你需要使用墊片來確保Array.prototype.filter定義舊的瀏覽器。

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 
0

下面是兩個,更明確的,VERSI @ jAndy接受了答案。

我做的第一個版本的自己,所以我能理解其中的邏輯更好,增加了以下內容:

如果該鍵不存在,增加了匹配的 對象的Count屬性,否則創建新的對象與1

在第二個版本的計數,我意識到,我寧願我的arrayOfObjects變量是一個object,這樣以後我可以專門針對值,而不是循環陣列上,直到我得到了一個比賽,然後獲得關聯nt對象值。因此該版本使用對象而不是對象數組。

版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>

相關問題