Jamgreen
Jamgreen

Reputation: 11039

Get values from object as list in javascript

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

Answers (2)

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

schnawel007
schnawel007

Reputation: 4020

var values = [];
for(var k in obj) values .push(obj[k]);

values will contain the values of the array

Upvotes: 1

Related Questions