Object.values() in jQuery
Solution 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"]
}
Solution 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.)
Solution 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() { ... }
indieman
Updated on July 30, 2022Comments
-
indieman almost 2 years
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?