简体   繁体   中英

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?

I don't think there's a method that does it directly, but you can use $.map() :

$.map(myObj, function(val, key) { return val; }); //returns ["val1", "val2"]

(Note though that if the callback returns null or undefined for a given property that item will not be included in the new array, so if your object might have properties with those values you'll have to do it another way. It's pretty easy to code from scratch though, with a for..in loop.)

prototypejs' values method extends JavaScript's builtin Object object. There's nothing stopping you from doing the same:

Object.values = function(object) {
  var values = [];
  for(var property in object) {
    values.push(object[property]);
  }
  return values;
}


var foo = {a:1, b:2, c:3};
console.log(Object.values(foo));
// [1, 2, 3]

Alternatively, you can add the method described above to the jQuery object if you'd rather not tamper with Object :

$.values = function() { ... }

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"]
}

Underscorejs has the _.values method: _.values({one : 1, two : 2, three : 3}); => [1, 2, 3] _.values({one : 1, two : 2, three : 3}); => [1, 2, 3]

This library augments JQuery very well - as well as working wonderfully in prototypejs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM