javascript根据关联数组键值从数组中查找值
问题描述:
我有一个关联数组:
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
我正在使用jQuery,所以我有
I am using jQuery so I have
$.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
}
答
在array_order
而不是array1
上更轻松,更快地进行迭代:
Easier and faster iterate over array_order
instead of 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];
}
}
也可以实现对array1
属性的迭代,但这要慢得多:
Iteration over array1
properties can be realized also, but it's significantly slower:
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];
}
}
而且jQuery中也不需要.
And there is no need in jQuery.