Search code examples
javascriptjqueryprototypejs

Object.values() in jQuery


The prototypeJS library has a method Object.values() which returns an array of values in an object.

EG:

 var myObj = {
   "key1" : "val1"
   "key2" : "val2"
 }
 Object.values(myObj) //returns ["val1", "val2"]

is there a jQuery method that does the same thing?


Solution

  • Using ES6, you can do the following:

    Object.values = x =>
            Object.keys(x).reduce((y, z) =>
                y.push(x[z]) && y, []);
    

    This simply returns an array containing the object's values. No need for JQuery, _ or anything else.


    note: Object.values() is currently in draft for ES7

    Using babel, installing

    • babel-preset-es2017
    • babel-plugin-transform-runtime

    gives support for Object.values/Object.entries as well as other ES2017 functionality.

    As per recommendation by the modules, configure the .babelrc file with the following:

    {
      "plugins": ["transform-runtime"],
      "presets": ["es2017"]
    }