What the question says...
Does jQuery have any methods that will allow you to query a mult-dimensional array of objects in a similar fashion as it does with the DOM.
So for instance, get me a list of objects contained within a multi-dimensional array having some matching property value - for instance where StartOfPeriod greater than a specified date or where name == "Ben Alabaster"
I'd like to avoid re-inventing the wheel if there's something already out there.
Javascript has no inbuilt support for multidimensional arrays, however the language is flexible enough that you can emulate this behaviour easily by populating your arrays with separate arrays, creating a multi-level structure.
Learn how to loop through elements, arrays and objects with jQuery using the $. each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.
A multidimensional array is an array that contains another array. For example, // multidimensional array const data = [[1, 2, 3], [1, 3, 4], [4, 5, 6]];
The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
You can't use selector syntax, but jQuery comes with $.grep and $.inArray, which can be useful for this. grep
returns a new array of elements that match a predicate. inArray
returns the index of the first matching element, or -1. For instance:
var matches = $.grep(array, function(el){
return el.StartOfPeriod > 2000;
});
These are similar to the standard ECMAScript methods, Array.filter
(simimlar to grep
) and Array.indexOf
(similar to inArray
); jQuery actually uses Array.indexOf
where available. There are also other useful ECMAScript methods, such as Array.every
(all elements matching) and Array.some
(at least one matching). MDC has code you can add to your project so these work in browsers that don't have native implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With