0

I have a quick question about returning the values from an object using JavaScript.

More specifically I want to write a function that takes an object as a parameter and then returns the values in an array.

I know that its easy to do this with the object keys as one can just use object.keys(), but I was wondering if there was a good way to do this for values?

Sorry if this is a basic question, I've done some searching around and can't seem to find anything that helps.

DVK
  • 126,886
  • 32
  • 213
  • 327
John Smith
  • 591
  • 1
  • 4
  • 4
  • If one only wants the values and not the keys, then perhaps you should change the calling code to use an array instead of an object since the array has only values and it's easier to access the list of values in an array. – jfriend00 Dec 28 '14 at 02:36

3 Answers3

1

You can iterate through the object, push the values to an array, and then return that:

var grabValues = function(obj){
  var results = [];

  for(var key in obj){
    results.push(obj[key]);
  }

  return results;
};
0

There are a lot of javascript resources that can help with this, but here is an example function.

function obj2array(o) {
  var arr=[];
  for(var x in o) {
    arr.push(o[x]);  
  }
  return arr;
}
Born2Code
  • 1,055
  • 6
  • 13
0

Third post here is quite explanatory on accessing Object values. In your case, you just access each value by key and push it into an array.

Community
  • 1
  • 1
VHarisop
  • 2,816
  • 1
  • 14
  • 28