Alternative version for Object.values()

前端 未结 11 1716
花落未央
花落未央 2020-11-28 06:13

I\'m looking for an alternative version for the Object.values() function.
As described here the function is not supported in Internet Explorer.

When

相关标签:
11条回答
  • 2020-11-28 06:57

    Object.values() is part of the ES8(June 2017) specification. Using Cordova, I realized Android 5.0 Webview doesn't support it. So, I did the following, creating the polyfill function only if the feature is not supported:

    if (!Object.values) Object.values = o=>Object.keys(o).map(k=>o[k]);
    
    0 讨论(0)
  • 2020-11-28 07:07

    You can get array of keys using Object.keys(). This will work in IE also. Object.values() is not required at all to get values since we can use the keys obtained from Object.keys() to get values as below:

    var obj = { foo: 'bar', baz: 42 };
    var keyArray = Object.keys(obj);
    for(var i = 0; i < keyArray.length; i++)
        console.log(obj[keyArray[i]]); 
    
    0 讨论(0)
  • 2020-11-28 07:08

    You can use a polyfill:

    const valuesPolyfill = function values (object) {
      return Object.keys(object).map(key => object[key]);
    };
    
    const values = Object.values || valuesPolyfill;
    
    console.log(values({ a: 1, b: 2, c: 3 }));

    0 讨论(0)
  • 2020-11-28 07:13

    var x = {Name: 'John', Age: 30, City: 'Bangalore'};
     
    Object.prototype.values = function(obj) {
                                    var res = [];
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                res.push(obj[i]);
            }
        }
        return res;
    };
     
    document.getElementById("tag").innerHTML = Object.values(x)
    <p id="tag"></p>

    0 讨论(0)
  • 2020-11-28 07:13

    As I didn't found an answer for my needs:

    var obj = { foo: 'bar', baz: 42 };
    
    
    console.log(obj[Object.keys(obj)[0]]) // bar
    
    console.log(obj[Object.keys(obj)[1]])  // 42

    Using the possibility of objects to adress them per literal.

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