在javascript中搜索字典数组中的id

时间:2014-07-07 08:15:32

标签: javascript arrays dictionary

我在JavaScript中有一个字典数组,我希望通过匹配(如果找到ID)将元素添加到数组中的一个字典中。 如何搜索是否找到了ID?

这是我的字典:

{ 
    priyanka: [ { socketid: 'bVLmrV8I9JsSyON7AAAA' } ],
    test: [ { socketid: 'Q2n5RzcJqPeLZ5T9AAAB' } ] } ] 
}

我想通过搜索socketid" bVLmrV8I9JsSyON7AAAA"来添加元素。并在字典中添加一个元素。

5 个答案:

答案 0 :(得分:2)

在数据的当前状态下,您至少必须使用线性搜索。

var keyToFind = 'Q2n5RzcJqPeLZ5T9AAAB';
for(var i in dictionary){
    if(dictionary[i].socketid == keyToFind){
        // Add an element to the dictionary
        break; // If you want to break out of the loop once you've found a match
    }
}

答案 1 :(得分:0)

var myObject = { 
    priyanka: [ { socketid: 'bVLmrV8I9JsSyON7AAAA' } ],
    test: [ { socketid: 'Q2n5RzcJqPeLZ5T9AAAB' } ] } ] 
};

myObject.priyanka.forEach(function(item){
    if(item.socketid === 'bVLmrV8I9JsSyON7AAAA'){
        // There is a socketid equals to bVLmrV8I9JsSyON7AAAA in priyanka
        break;
    } else {
        // Socketid not found
    }
});

请注意,Array.forEach并非完全跨浏览器兼容,您可能希望使用简单的for循环:

for(var i=0; i < myObject.priyanka.length; i++){
    if(myObject.priyanka[i].socketid === 'bVLmrV8I9JsSyON7AAAA'){
        // There is a socketid equals to bVLmrV8I9JsSyON7AAAA in priyanka
        break;
    } else {
        // Socketid not found
    }
}

答案 2 :(得分:0)

你的问题相当令人困惑,但我认为你要做的是:

var myDict = { 
    priyanka: [ { socketid: 'bVLmrV8I9JsSyON7AAAA' } ],
    test    : [ { socketid: 'Q2n5RzcJqPeLZ5T9AAAB' } ],
 }

然后循环遍历数组(尽管在这种情况下,它们只包含一个项目......)

var arr = myDict.priyanka
for(var i=0; i<arr.length ; i++){
    if(arr[i].socketid === 'bVLmrV8I9JsSyON7AAAA'){
        var el = /whatever you wanna add?/
        arr.push(el);
       }
}

答案 3 :(得分:0)

你可以添加像这样的元素

字典

var dict = { 
priyanka: [ { socketid: 'bVLmrV8I9JsSyON7AAAA' } ],
test: [ { socketid: 'Q2n5RzcJqPeLZ5T9AAAB' } ] }

功能

var addToDict = function (dict,id,element) {
    for(key in dict){   //search in each key of dictionary
       var obj = dict[key];
       if(obj[0].socketid == id)   // if that key contains socketId
         obj.push(element);    // add element to key's array
    }
}

调用函数

addToDict(dict,'bVLmrV8I9JsSyON7AAAA',{"word":"meaning"}) 
console.log(dict)  // because object will be passed by reference the `dict` will changed.

答案 4 :(得分:0)

您可以使用此辅助功能:

function findInDict(dict, predicate) 
{
    for (var prop in dict) {
        if (dict.hasOwnProperty(prop) && predicate(dict[prop], prop, dict)) {
            return prop;
        }
    }
    return null;
  };
}

然后执行搜索:

// find property on main dictionary
var prop = findInDict(dict, function(value, name) {
    // name is property name
    // value is property value
    return value[0].socketid == 'bVLmrV8I9JsSyON7AAAA';
});

if (prop === null) {
    // prop doesn't exist, so create one?
}