Reputation: 2076
Let's say I have this (admittedly bad) structure:
var items = [
{SomeString: [value1,value2...]},
{AnotherString: [valueX,valueY...]},
{YetAnotherString: [valueA,valueB...]}
];
I want to obtain the array assigned to "AnotherString".
One way (via jQuery) I am using:
$.each(items,function(x,item){
$.each(item,function(key,values){
if(key=="AnotherString"){
//...do something
}
}
});
Obviously this is terribly inefficient, as it loops through needless items. One way would be to refactor it in a "while(!found)" loop.
My question: what's the most efficient way to filter through such an array?
Edit: forgot to clarify that I do not know in advance the key strings. This is used in an external loop where the key strings I am looking for are passed down.
Upvotes: 0
Views: 248
Reputation: 215019
If you know that this structure is bad, why do you stick to it? Just use a normal object:
var obj = {
SomeString: [value1,value2...],
AnotherString: [valueX,valueY...],
YetAnotherString: [valueA,valueB...]
};
If this is not possible for some reason, convert it dynamically:
obj = {};
items.forEach(function(item) {
var key = Object.keys(item)[0];
obj[key] = item[key];
});
This returns an object like the above. Once you have this, just do obj[someKey]
when needed. No loops.
(This assumes, of course, that all keys are different).
Upvotes: 2
Reputation: 324760
Sometimes, stripping away jQuery and using Vanilla JS is the route to the most efficient solution.
items.some(function(item) {
if( item.hasOwnProperty("AnotherString")) {
// do something with item["AnotherString"]
return true;
}
return false;
});
Documentation on the some
function - Polyfill provided
Upvotes: 3