Alternative version for Object.values()

前端 未结 11 1685
花落未央
花落未央 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:48

    You can get array of keys with Object.keys() and then use map() to get values.

    var obj = { foo: 'bar', baz: 42 };
    var values = Object.keys(obj).map(function(e) {
      return obj[e]
    })
    
    console.log(values)

    With ES6 you can write this in one line using arrow-functions.

    var values = Object.keys(obj).map(e => obj[e])
    
    0 讨论(0)
  • 2020-11-28 06:52

    Best way is to replace it with the values method of ramda:

    import * as R from 'ramda';
    
    const obj = { foo: 'bar', test: 10 };
    
    console.log(R.values(obj)) // ['bar', 10]

    0 讨论(0)
  • 2020-11-28 06:54

    Since Object is a (not so) recent implementation, if you want to support all browsers (AKA IE8 and below), then you need to create your own function:

    function objectValues(obj) {
        var res = [];
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                res.push(obj[i]);
            }
        }
        return res;
    }
    

    PS: Just noticed the ecmascript-6 tag. Btw I keep this answer here, just in case someone needs it.

    0 讨论(0)
  • 2020-11-28 06:55

    If you are already using core-js (e.g. by using Angular) you can just import the according polyfill:

       import 'core-js/es7/object';
    
    0 讨论(0)
  • 2020-11-28 06:56

    For people using UnderscoreJS, you can get object values by using _.values :

    var obj = { foo: 'bar', baz: 42 };
    console.log(_.values(obj)); // ['bar', 42]
    
    0 讨论(0)
  • 2020-11-28 06:56

    I know it is a old topic. I was playing arround and just want to add another implementation. It is simply the map version with the map itself implemented with a reduce :

    let obj = { foo: 'bar', baz: 42 };
    
    const valueArray = Object.keys(obj).reduce((acc, key) => {
      acc.push(obj[key]);
      return acc;
    }, []);
    
    console.log(valueArray);

    It does the job but it has something that bother me. The reducer function uses obj and the obj was not injected in it. We should avoid global variable inside functions and make our functions more testable. So I do prefer this version with a reducer function helper that takes the obj as parameter an return the actual reducer function . It becomes:

    let obj = { foo: 'bar', baz: 42 };
    
    // reducer function helper take obj and return the actual reducer function
    let reducerFuncHelper= obj => (acc, key) => {
      acc.push(obj[key]);
      return acc;
    }
    //much better
    const valueArray = Object.keys(obj).reduce(reducerFuncHelper(obj), []);
    console.log(valueArray);

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