How to read value from JSON object?

70 views Asked by At

I'm trying to read individual value from be json array object to display in the page. I have tried with below code but couldn't make it. Please advise what am i doing wrong here.

Apperciate your help.

2

There are 2 answers

5
TimoStaudinger On

You can get the length of a JavaScript array via its property length. To access the array Reference in your object, you can use dot notation.

In combination, the following should do what you expect:

var obj = {
    "Reference": [
        {
            "name": "xxxxxxxx",
            "typeReference": {
                "articulation": 0,
                "locked": false,
                "createdBy": {
                    "userName": "System",
                },
                "lastModifiedBy": {
                    "userName": "System",
                },
                "lastModified": 1391084398660,
                "createdOn": 1391084398647,
                "isSystem": true
            },
            ...
        },
        ...
    ]
};

console.log(obj.Reference.length);

In case you are actually dealing with a JSON string, not a JavaScript object, you will need to parse it first via JSON.parse().

0
MoeSattler On

You get the length of an array by simply access the length attribute. For example [0,1,2,3].length === 4.

If you just want to loop through the array, use forEach or map instead of a for loop. It's safer, cleaner, less hassle and you don't meed to know the length.

E.g.

[0,1,2,3].forEach(num => console.log(num))