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];
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];
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];
});
You can get values from this object without looping using Object.values()
method like:
var output = Object.values( input );
console.log( output ); // [2, 6, 4]
DEMO:
var input = {
'foo': 2,
'bar': 6,
'baz': 4
};
var output = Object.values( input );
console.log( output );
PLEASE NOTE:
This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.
So, currently it supports Chrome & Firefox only.
I don't know why you want without loop . here my solution
JSON.stringify( input ).replace(/"(.*?)"\:|\{|\}/g,'' ).split(',')
it print [2, 6, 4]
. I didn't test for other json values
var input = {
'foo': 2,
'bar': 6,
'baz': 4
};
var newArr = new Array;
$.each(input,function(key,value) {
newArr.push(value);
});
alert(newArr)