简体   繁体   English

javascript根据关联数组键值从数组中查找值

[英]javascript find value from array based on associative array key value

I have an associative array: 我有一个关联数组:

var array1 = {
    a1: {
        id: "box1",
        title: "box 1"
    },
    a2: {
        id: "box2",
        title: "box 2"
    },
    a3: {
        id: "box3",
        title: "box 3"
    }
};

I then have another array which has references to the first array: 然后,我还有另一个引用第一个数组的数组:

var array_order = ["a3:positionA", "a2:postitionB", "a1:positionC"];

I want to loop through the first list and then use the second list to find the position text 我想遍历第一个列表,然后使用第二个列表查找位置文本

I am using jQuery so I have 我正在使用jQuery,所以我有

$.each(array1, function(i,o) {
  something in here where I can use i to find out what position. e.g. if a1 I would get positionC
}

Easier and faster iterate over array_order instead of array1 : array_order而不是array1更轻松,更快速地进行迭代:

for( var i = 0, len = array_order.length; i < len; i++ ) {
    var ref = array_order[i].split(':');

    if( ref.length === 2 && ({}).hasOwnProperty.call( array1, ref[0] ) ) {
        var array1Property = array1[ ref[0] ];
        var array1PropertyPosition = ref[1];
    }
} 

Iteration over array1 properties can be realized also, but it's significantly slower: 也可以实现对array1属性的迭代,但是它要慢得多:

for( var prop in array1 )
    if( ({}).hasOwnProperty.call( array1, prop ) )
        for( var i = 0, len = array_order.length; i < len; i++ ) {
            var ref = array_order[i].split(':');
            if( ref.length === 2 && prop === ref[1] ) {
                var array1Property = array1[ prop ];
                var array1PropertyPosition = ref[1];
            }
        }

And there is no need in jQuery. 而且jQuery中没有必要。

Ok first things first JS calls associative arrays as objects only. 好的,首先,JS只将关联数组称为对象。

next to iterate over each key in object 遍历对象中的每个键

for(var prop in array1) {
    if(array1.hasOwnProperty(prop))
        for(key in array_order){
           if( key === prop){
           doSomethingwith(array_order[key]);

           }

        }
}
var temp_array_order = {};
$.each(array_order, function(key, val) { 
    temp_array_order[val.substr(0,2)] = val.substr(3); 
};
$.each(array1, function(key, val) {
    var category = temp_array_order[key];
    ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM