how to fetch array keys with jQuery?

前端 未结 6 794
北海茫月
北海茫月 2020-12-03 04:19

Good afternoon. I have an array with some keys, and values in them. I then need to fetch the array keys and not the data in them. I want to do this with jQuery. I know for e

相关标签:
6条回答
  • 2020-12-03 04:58
    console.log( Object.keys( {'a':1,'b':2} ) );
    
    0 讨论(0)
  • 2020-12-03 05:00

    Using jQuery, easiest way to get array of keys from object is following:

    $.map(obj, function(element,index) {return index})
    

    In your case, it will return this array: ["alfa", "beta"]

    0 讨论(0)
  • 2020-12-03 05:01

    Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way

    var foo = {};
    foo['alfa'] = "first item";
    foo['beta'] = "second item";
    
    for (var key in foo) {
            console.log(key);
    }
    

    Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.

    EDIT:

    In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -

    • "Associative Arrays" considered Harmful
    0 讨论(0)
  • 2020-12-03 05:05

    I use something like this function I created...

    Object.getKeys = function(obj, add) {
        if(obj === undefined || obj === null) {
            return undefined;
        }
        var keys = [];
        if(add !== undefined) {
            keys = jQuery.merge(keys, add);
        }
        for(key in obj) {
            if(obj.hasOwnProperty(key)) {
                    keys.push(key);
            }
        }
        return keys;
    };
    

    I think you could set obj to self or something better in the first test. It seems sometimes I'm checking if it's empty too so I did it that way. Also I don't think {} is Object.* or at least there's a problem finding the function getKeys on the Object that way. Maybe you're suppose to put prototype first, but that seems to cause a conflict with GreenSock etc.

    0 讨论(0)
  • 2020-12-03 05:06

    you can use the each function:

    var a = {};
    a['alfa'] = 0;
    a['beta'] = 1;
    $.each(a, function(key, value) {
          alert(key)
    });
    

    it has several nice shortcuts/tricks: check the gory details here

    0 讨论(0)
  • 2020-12-03 05:13

    Don't Reinvent the Wheel, Use Underscore

    I know the OP specifically mentioned jQuery but I wanted to put an answer here to introduce people to the helpful Underscore library if they are not aware of it already.

    By leveraging the keys method in the Underscore library, you can simply do the following:

    _.keys(foo)  #=> ["alfa", "beta"]
    

    Plus, there's a plethora of other useful functions that are worth perusing.

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