How to use Object.values() on server side in Node.js

前端 未结 7 1255
不思量自难忘°
不思量自难忘° 2020-12-03 00:46

Object.values() received following error:

TypeError: Object.values is not a function.

From this question on stack

相关标签:
7条回答
  • 2020-12-03 00:48

    Object.values() is in status "Draft" for the version ECMAScript2017 and here the specification: ECMAScript 2017 Draft (ECMA-262) The definition of 'Object.values' in that specification..

    The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

    Without change nothing in your NodeJS enviroment you can achive the same by using Object.keys() that returns an array of keys and chaining a Array.prototype.map() method to return the desired array of the Object's values:

    const obj = { 
        foo: "bar", 
        baz: 42 
      },
      // Object.values()
      objValues = Object.values(obj),
      // Object.keys() and map(),
      objKeysMap = Object.keys(obj).map((k) => obj[k]);
    
    console.log('objValues:', objValues);
    console.log('objKeysMap:', objKeysMap);

    0 讨论(0)
  • 2020-12-03 00:48

    Upgrade your Node.js to the latest version. It'll enable you to use

    Object.values()
    

    You can get it from the official site: https://nodejs.org/en/download/current/

    It worked for me :)

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

    Lodash is a pretty awesome tool to simplify your JavaScript code. You can use _.values:

    var _ = require('lodash');
    _.values({ a: 'a' }) // => ['a']
    
    0 讨论(0)
  • 2020-12-03 01:10

    Object.values is a new feature in ES2017. It is very bleeding edge. Node.js has full support for it from version 7.0.

    6.8.1 supports it, but it is considered unstable and is locked behind the --harmony flag.

    You can either:

    • Upgrade to the latest Node.js LTS and use --harmony
    • Upgrade to the latest Node.js Current
    • Use a polyfill
    0 讨论(0)
  • 2020-12-03 01:13

    Here's a polyfill that kicks in only when it's not already defined:

    const objectToValuesPolyfill = (object) => {
      return Object.keys(object).map(key => object[key]);
    };
    Object.values = Object.values || objectToValuesPolyfill;
    
    0 讨论(0)
  • 2020-12-03 01:15

    I am developing a AWS Lambda and now I stumbeled over the same problem and I solved it by this simple line (assuming a is the object) const values = Object.keys(a).map(k => a[k]);

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