JavaScript, transform object into array

前端 未结 9 1930
孤城傲影
孤城傲影 2020-12-14 15:58

I\'ve got an object:

var obj = {
    \"Mike\": 24,
    \"Peter\": 23,
    \"Simon\": 33,
    \"Tom\": 12,
    \"Frank\": 31
};

I want to cr

相关标签:
9条回答
  • 2020-12-14 16:19

    Some libraries have something to do this (such as prototype's "values" function), but they're really just wrappers around a function that loops over and returns the values of the object.

    http://www.prototypejs.org/api/object/values

    0 讨论(0)
  • 2020-12-14 16:20

    Posting this strictly for fun. Save your downvotes. I'm not recommending it actually be used. ;o)

    Example: http://jsfiddle.net/WGpXX/

    var arr = eval( '[' +
        JSON.stringify(obj)
        .slice(1,-1)
        .replace(/"[^"]+":/g,'')
        + ']');
    

    Technically works in this simple case.

    0 讨论(0)
  • 2020-12-14 16:22

    Try this:

    var obj = {     "Mike": 24,     "Peter": 23,     "Simon": 33,     "Tom": 12,     "Frank": 31 } ;
        var arr = []
        for(var a in obj)
        {
            var val = obj[a];
            arr.push(val);
        }
    alert(arr.length)
    
    0 讨论(0)
  • 2020-12-14 16:31

    With jQuery you could use the each function:

    var obj = {
        "Mike": 24,
        "Peter": 23,
        "Simon": 33,
        "Tom": 12,
        "Frank": 31
    }
    
    myArray=new Array();
    $.each(obj, function(key, value) { 
      myArray.push(value);
    });
    
    0 讨论(0)
  • 2020-12-14 16:32

    Use Object.values it will return array.

    Object.values(obj) // [24, 23, 33, 12, 31]
    
    0 讨论(0)
  • 2020-12-14 16:36

    The obvious way would be to do a for-in loop, as @quixoto suggests, but just for the record, and since you are looking for a built-in way, you could pair the new ECMAScript 5 methods Object.keys and Array.prototype.map, available on latest browsers:

    function valuesToArray(obj) {
      return Object.keys(obj).map(function (key) { return obj[key]; });
    }
    

    UPDATE: ES2017 introduced the Object.values method, which does exactly what you want.

    Additionally, ES2017 adds another often useful method, Object.entries. This method returns an array of key-value pairs.

    const obj = {
        "Mike": 24,
        "Peter": 23,
        "Simon": 33,
        "Tom": 12,
        "Frank": 31
    };
    
    const values = Object.values(obj);
    const entries = Object.entries(obj);
    console.log('values:', values);
    console.log('entries:', entries);

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