0

I have write this code to access object value in loop but it won't let me access in loop I am getting console error but when I access each value individually I don't get any error.

<!DOCTYPE html>
    <html>
    <head>
    <title></title>
</head>
<body>

<script type="text/javascript">
    var keys;
    var obj = [{"id":"1","firstname":"Aftab","lastname":"Altaf"},{"id":"2","firstname":"Haris","lastname":"Jaliawala"},{"id":"3","firstname":"Muzammil","lastname":"Mumtaaz"}];

    for(key in obj)
    {
        keys = Object.keys(obj[key]);
    }

    console.log(obj[0].firstname);

    for(value in obj)
    {
        console.log(obj[value].keys[value]);
    }

</script>
</body>
</html>

This is the output I am getting in my console. OUTPUT

Aftab
Uncaught TypeError: Cannot read property '0' of undefined

Anyone please help?

1
  • obj is an array, doesn't matter if you call it obj, it's still an array, and arrays are iterated with regular for loops, and the iteration only stores the last iteratet keys in the variable keys, not all of them, so it's basically all just wrong. Commented Dec 29, 2013 at 11:07

2 Answers 2

1

inplace of

console.log(obj[value].keys[value]);

use

console.log(obj[value][keys[value]]);
Sign up to request clarification or add additional context in comments.

Comments

1

When you want to access a dinamic property of an object in javascript -

you have to use [] and not dot notation.

Thats why you have to use console.log(obj[value][keys[value]]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.