Reputation: 11039
With
a = {2: "test", 3: "test2"};
console.log(Object.keys(a));
I get a list ["2", "3"]
.
Does there exists a function like Object.keys()
for the values instead?
I have tried Object.values(a)
but it doesn't work.
Upvotes: 0
Views: 2740
Reputation: 12004
In JavaScript there is no values()
method for objects. You can get values using a iteration, eg:
//using for ... in
var a = {2: "test", 3: "test2"};
var values = [];
for(var key in a){
values.push(a[key])
}
//Or just use `Array.map()` working with object keys:
var a = {2: "test", 3: "test2"};
var values = Object.keys(a).map(function(key){
return a[key]
});
Implementing Object.values()
:
Object.values = function(obj){
return Object.keys(obj).map(function(key){
return obj[key]
})
}
var a = {2: "test", 3: "test2"};
console.log(Object.keys(a));
console.log(Object.values(a));
Upvotes: 2
Reputation: 4020
var values = [];
for(var k in obj) values .push(obj[k]);
values will contain the values of the array
Upvotes: 1