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];
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.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
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.
var arr = $.map(input,function(v){
return v;
});
Demo -->
http://jsfiddle.net/CPM4M/
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];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With