可以說我有散列的數組:查找和更新由HashKey哈希添加記錄保存
而且我想找到一個哈希並添加到它。例如找到「一」,並添加:
hash = [{"one": 1, "new": new}, {"two": 2}]
我可以通過散列鍵做到這一點?如果是的話,我會怎麼做呢?或者有更好的方法來在JavaScript中做這件事情?我不想複製散列,做一個新的並刪除舊的。只需更新已有的內容即可。
可以說我有散列的數組:查找和更新由HashKey哈希添加記錄保存
而且我想找到一個哈希並添加到它。例如找到「一」,並添加:
hash = [{"one": 1, "new": new}, {"two": 2}]
我可以通過散列鍵做到這一點?如果是的話,我會怎麼做呢?或者有更好的方法來在JavaScript中做這件事情?我不想複製散列,做一個新的並刪除舊的。只需更新已有的內容即可。
JavaScript是非常動態的,所以你應該能夠做這樣的事情:
var hash = [{"one": 1}, {"two": 2}];
var hLength = hash.length;
for(int i=0; i<hLength; i++){ // Loop to find the required object.
var obj = hash[i];
if(obj.hasOwnProperty('one')){ // Condition you're looking for
obj["new"] = "new"; // Property you wish to add.
break;
}
}
這是一個功能我剛寫來做到這一點。
/*
* hashes - (array) of hashes
* needle - (string) key to search for/(int) index of object
* key - (string) key of new object you wish to insert
* value - (mixed) value of new object you wish to insert
*/
function addToHash(hashes, needle, key, value) {
var count = hashes.length;
// If needle is a number treat it as an array key
if (typeof needle === 'number' && needle < count) {
hashes[needle][key] = value;
return true;
} else {
// Search hashes for needle
for (var i=0; i<count; i++)
{
if (needle in hashes[i]) {
hashes[i][key] = value;
return true;
}
}
}
return false;
}
可以針是$$ hashkey? – 2013-02-24 18:33:43
@CharlieDavies我不確定$$的重要性,但是如果$$ hashkey是一個字符串,那就是哈希中的一個鍵的名字,那麼是的。或者你的意思是別的嗎? – 2013-02-24 18:39:35
如果你樂於使用通過起下劃線,你可以把它做:
var hashes = [{"one": 1}, {"two": 2}];
var changed = _.map(hashes, function(hash){
if(hash.one) {
hash["new"] = "new";
return hash
}
return hash;
});
你可以通過傳遞一個過濾功能概括有點封裝的if語句,另一個函數來封裝哈希的修改。
編輯如果你想推廣到尋找在哈希什麼,這可能是工作:
var hashes = [{"one": 1}, {"two": 2}];
var isOne = function(hash) {
return hash.one;
}
var addNew = function(hash) {
hash["new"] = "new";
return hash;
}
var hashChanger = function(filter, editor) {
return function(hash) {
if(filter(hash)) {
return editor(hash);
}
return hash;
}
}
var changed = _.map(hashes, hashChanger(isOne, addNew));
我怎麼能這樣做,但不需要知道散列?在這個例子中它是一個。然而,他們將是動態的。散列鍵? – 2013-02-24 18:25:39
我已編輯答案以嘗試回答此問題。 – 2013-02-24 18:27:44
,你會很高興的使用圖書館,像underscore.js? – 2013-02-24 18:11:59
是的,我使用它已爲一些 – 2013-02-24 18:12:27