Get key value of dictionary by index in jQuery

那年仲夏 提交于 2019-12-06 20:05:40

问题


I have a javascript dictionary object which has a pre-set keys that are defaulted to 0. Then I need to loop through the elements of this dictionary by index and use the value of the key to set its value. Below is my code to make things easier to understand:

var _map = {
    'severity-normal': 0,
    'severity-minimal': 0,
    'severity-moderate': 0,
    'severity-severe': 0,
    'severity-highly-severe': 0
};

    mapSeverities: function () {
        for (var i = 0; i < _map.length; i++) {
            //get the key value, ex: severity-normal, by index (which would by i)
            var key = //retrieved key value
            _map[key] = this.data(key);
        }
    }

In other words, suppose we're dealing with C#, I want to get the KeyValuePair at a certain index, then access its Key and Value properties.

Any suggestions?


回答1:


For object _map, you should use for .. in.

for (var key in _map) {
  _map[key] = this.data[key];
}



回答2:


You can also use $.each like this

$.each(_map, function(key, value) { 
  // key is the key
  // value is the value
});

Working Fiddle



来源:https://stackoverflow.com/questions/10894484/get-key-value-of-dictionary-by-index-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!