neelmeg
neelmeg

Reputation: 2509

cant seem to loop through object keys

I have an object through which im trying to loop through using for..in. But it gives me "0" as values instead of the object keys such as piidata, location, risklevel etc.

var srcObj = [{
    location: "34",
    piidata: "sdafa",
    risklevel: "Medium"
}]

for (var prop in srcObj) {
                console.log(prop);            
            }

object

Upvotes: 0

Views: 85

Answers (6)

rswerve
rswerve

Reputation: 179

Your srcObj is an array. You can tell by the square brackets [] it's enclosed in. But Chrome says Object. Right. Javascript types are a little strange. Check out this page.

If you want to access the key/values in the object, you can specify the index of the object within the array. srcObj[0] in this case. If you want to get the object out of the array and deal with it just as an object, you can do something like this:

var trueObject = srcObj.shift()

Which removes and returns the first element of an array and assigns it to your variable.

Upvotes: 0

Mike
Mike

Reputation: 787

All you need to do

for (var prop in srcObj) {
  console.log(srcObj[prop]);
  console.log(srcObj[prop]["risklevel"]); // --> Medium

  var keyNames = Object.keys(srcObj[prop]); // --> return keyNames as array
  console.log(keyNames[0], keyNames[1]); // --> location   piidata
}

Upvotes: 0

Satish Kumar sonker
Satish Kumar sonker

Reputation: 1288

while you are looping the javascript object it's return the index/key of object

so if you are trying to get value of each key try.

for( var prop in srcObj ) 
{
    console.log(srcObj[prop]);            
}

if you are trying to get each key name then try this one

for( var prop in srcObj ) 
{
    console.log(prop);            
}

Upvotes: 0

BenM
BenM

Reputation: 53228

Your srcObj is actually an array (identified by the [ and ] literals) which contains an object as its only element.

To access the parameters of the single object inside the array, use the following syntax:

for( var prop in srcObj[0] ) 
{
    console.log(prop);            
}

jsFiddle Demo

Upvotes: -1

Joseph Marikle
Joseph Marikle

Reputation: 78540

Your "srcObj" is an array. This is indicated by the wrapping [ ... ]. If you console.log srcObj[0], you should get the object itself.

Upvotes: 1

deceze
deceze

Reputation: 522261

srcObj is an array, as evidenced by the []. Inside it is an object at index 0.

Upvotes: 3

Related Questions