Are there any jquery features to query multi-dimensional arrays in a similar fashion to the DOM?

前端 未结 3 522
有刺的猬
有刺的猬 2021-01-04 21:12

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.

相关标签:
3条回答
  • 2021-01-04 21:43

    I just wrote this.. I think it works properly but it could definitely get cleaned up :)

    function findMatchingObjects(obj, member, value){
       var final = new Array();
       var temp = new Array();
       for(var p in obj){
        if (typeof obj[p] == 'object' ) {
         temp = findMatchingObjects(obj[p], member, value);
         if (temp.length == 1)
          final.push(temp[0]);
        }
        if (p == member && obj[p] == value) {
         final.push(obj);
        }
       }
       alert(final.length);
       return final;
    }
    

    Use it like so:

    var moo ={baz: 1, boo: 2, bar:{c1: 3, c2: 4, c3:{t:true, f:false, baz:1}},d: 11};
    var foo = findMatchingObjects(moo, "baz", 1);
    
    // did it work?
    console.log(foo);
    

    Returns an array of object (or sub-objects) that match the member-value pair. In this case, foo contains both moo and c3 since both of the objects contain a baz = 1 pair.

    Making the function look and feel like a jQuery selector is just a matter of syntactic sugar.

    0 讨论(0)
  • 2021-01-04 21:46

    You may find a plugin, but not in the jQuery core. There are a few helpful array methods: each, unique, inArray. In combination, you could create something custom to meet your needs.

    What you are searching for is more of a set library with xpath like traversal. Prototype has a much larger set of array methods. But still probably wouldn't meet your exact needs out of the box.

    I agree with alex, such a library/extension would be interesting.

    0 讨论(0)
  • 2021-01-04 21:57

    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.

    0 讨论(0)
提交回复
热议问题