1

This may be simple question, but i tried a lot and i can't find the solution. My problem is i want to loop through an object and get the properties of the object.

My object look like this:

{ value1: '0.92',
  value2: '3728104',
  value3: '43',
  value4: '0.66',      
}

I want to get value1, value2, value3, value4

My code:

 console.log("bbbbb=" +util.inspect(results));
        for (var prop in results) {
            console.log("Inside for");----------------------> This is printing once.
            keys.push(prop);
            console.log("After push");--------------------->This is not printed..
        }           
        console.log("keys=" +keys)

But its not looping ,, Help me to solve this.. Thanks in advance..

6
  • Basic debugging: log prop to see what it is Commented Mar 31, 2014 at 5:18
  • 2
    it should work fine... your code outputs ["value1", "value2", "value3", "value4"] for console.log(keys); Isnt that what you want..? Commented Mar 31, 2014 at 5:18
  • Yes @Sudhir ..i want that but keys is not printing.. Commented Mar 31, 2014 at 5:24
  • @Subburaj see this:: jsfiddle.net/quwLW Commented Mar 31, 2014 at 5:25
  • @sudhir nothing happens there?? Commented Mar 31, 2014 at 5:28

1 Answer 1

3

You can use Object.keys function like this

console.log(Object.keys(results));
# [ 'value1', 'value2', 'value3', 'value4' ]

Actually, your code has no problems at all

var results = {
    value1: '0.92',
    value2: '3728104',
    value3: '43',
    value4: '0.66',
};

var keys = [];
for (var prop in results) {
    keys.push(prop);
}

console.log(keys);
# [ 'value1', 'value2', 'value3', 'value4' ]
Sign up to request clarification or add additional context in comments.

5 Comments

If i put some console.log() b4 push statement its printing,but nothing below that..
@Subburaj Please show the actual code you used and show us the output of console.log(keys), after the loop.
@Subburaj Please try the code I have shown in the answer, as it is.
Ya that works...I am still confused..i have declared keys array globally.. thats the problem..
@Subburaj Most likely. Without seeing the actual code and the actual error, that is out best bet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.