0

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.

3
  • What do you want to do with the values? Commented Jul 1, 2015 at 12:06
  • Use it in allowedValues in a collection2 schema in Meteor. I save both the number and the name in my collection. Maybe I should avoid saving the name and always get the name from the dictionary :-D Thank you for making me realise Commented Jul 1, 2015 at 12:07
  • You could loop trough the objects and collect the values. Commented Jul 1, 2015 at 12:07

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

values will contain the values of the array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.