I have an object like
{ a: 2.078467321618,
b :13521.4,
c : 4503.9,
more...}
(In debug mode)
I want to loop through the object and separate key and value; How can I achieve this?
I have an object like
{ a: 2.078467321618,
b :13521.4,
c : 4503.9,
more...}
(In debug mode)
I want to loop through the object and separate key and value; How can I achieve this?
Object.keys(obj).forEach(function(key) {
var val = obj[key];
...
});
One more way to do it is to make it via foreach:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// do something with the key and obj[key], which is val
}
}
Note: here we check if the key belongs to our object, but not to its prototype via hasOwnProperty
method.
Try the following:
for(var key in object){
var value = object[key];
//now you have access to "key" and "value"
}
try something like this
for(var key in object){
alert(key);// will give key
alert(object[key]);// will give value
}
It's actually pretty simple:
for (var key in object) {
// do something with object[key]
}
Try this
var sum = 0;
var obj = {prop1: 5, prop2: 10, prop3: 15};
for each (var item in obj)
{
sum += item;
}
Result is sum = 5+10+15
Try the following code:
var keys=Array();
var values = Array();
for (var key in obj) {
//has own property is checked to bypass inherited properties like prototype
if (obj.hasOwnProperty(key)) {
keys.push(key)';
values.push(obj[key]);
}
}
//following are the keys and values separated,do whatever you want to do with them
console.log(keys);
console.log(values);
using jquery:
var obj = { a: 2.078467321618, b :13521.4, c : 4503.9 };
var keyArr = [];
var valArr = [];
//iterate obj
$.each(obj, function(k, v) {
//add items to the keyArr from obj's keys.
keyArr.push(k);
//add items to the varArr from obj's keys.
valArr.push(v);
});
//show the result
alert(keyArr);
alert(valArr);
see the demo: http://jsfiddle.net/bauangsta/KdZrA/