Object.values() in jQuery

為{幸葍}努か 提交于 2020-06-24 12:24:50

问题


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?


回答1:


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



回答2:


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.)




回答3:


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() { ... }



回答4:


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

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



来源:https://stackoverflow.com/questions/14791917/object-values-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!