Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object values without looping [duplicate]

I have following object:

var input = {
  'foo': 2,
  'bar': 6,
  'baz': 4
};

Is it possible to get values from this object without looping it ?

It is possible to use jQuery.

Expected result:

var output = [2, 6, 4];
like image 709
hsz Avatar asked May 24 '13 08:05

hsz


People also ask

Can you iterate objects?

There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.

Can object have same keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

What is object entries()?

Object.entries() returns an array whose elements are arrays corresponding to the enumerable string-keyed property [key, value] pairs found directly upon object . The ordering of the properties is the same as that given by looping over the property values of the object manually.


2 Answers

var arr = $.map(input,function(v){
 return v;
});

Demo --> http://jsfiddle.net/CPM4M/

like image 84
Mohammad Adil Avatar answered Oct 16 '22 06:10

Mohammad Adil


This is simply not possible without a loop. There's no Object.values() method (yet) to complement Object.keys().

Until then you're basically "stuck" with the below construct:

var values = [];

for (var k in input) {
  if (input.hasOwnProperty(k)) {
    values.push(input[k]);
  }
}

Or, in modern browsers (but of course still using a loop and an anonymous function call):

var values = Object.getOwnPropertyNames(input).map(function(key) {
    return input[key];
});
like image 6
Ja͢ck Avatar answered Oct 16 '22 06:10

Ja͢ck