-1

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.

5
  • json["Reference"].length Commented Dec 8, 2016 at 18:21
  • what do you mean by size? Commented Dec 8, 2016 at 18:21
  • 1
    object.keys should be Object.keys Commented Dec 8, 2016 at 18:22
  • please add the number you count. Commented Dec 8, 2016 at 18:22
  • I'm getting API response with about format.So after reference around 174 response from the server.I have verified through Online json viwer. Commented Dec 8, 2016 at 18:26

2 Answers 2

1

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().

5
  • http.request(options, function(res) { res.on('data', function (result) { console.log(res.Reference.length); Commented Dec 8, 2016 at 18:25
  • Why would you JSON.stringify() the result? Commented Dec 8, 2016 at 18:26
  • getting error TypeError: Cannot read property 'length' of undefined for console.log(obj.Reference.length); Commented Dec 8, 2016 at 18:33
  • That means that res does not have a property Reference. Are you sure that res contains your response? Commented Dec 8, 2016 at 18:35
  • yes , when i'm printing only res its showing all the JSON values. Commented Dec 8, 2016 at 18:39
0

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))

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.