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
$.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
:
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:
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.
Ok first things first JS calls associative arrays as objects only.
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];
...
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.