0

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?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Nandu
  • 3,076
  • 8
  • 34
  • 51

8 Answers8

1
Object.keys(obj).forEach(function(key) {
    var val = obj[key];
    ...
});
  • 2
    This implies that `keys` and `forEach` are implemented which will work in most modern browsers. But for IE you will need IE9 or higher. See http://kangax.github.io/es5-compat-table/ for more information on ECMA5 compatibility. – Chris Oct 22 '13 at 05:41
1

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.

aga
  • 27,954
  • 13
  • 86
  • 121
0
Try the following:

for(var key in object){
    var value = object[key];
    //now you have access to "key" and "value"
}
Chris
  • 7,675
  • 8
  • 51
  • 101
0

try something like this

for(var key in object){
    alert(key);// will give key
    alert(object[key]);// will give value
}
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
0

It's actually pretty simple:

for (var key in object) {
   // do something with object[key]
}
LesmoCasanova
  • 26
  • 1
  • 4
0

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

Prateek
  • 6,785
  • 2
  • 24
  • 37
0

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);
abhinsit
  • 3,214
  • 4
  • 21
  • 26
0

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/

Mox
  • 19
  • 4