Vishal Pandey
Vishal Pandey

Reputation: 41

JSON, jQuery and HTML

How to get the index of a particular object from a JSON file?

I have a JSON file with below content.

[
    {
        "time": "2017-04-11T22:31:50.3369265Z",
        "score": 0,
        "comment": "Meep meep!  ",
        "handle": "@roadrunner"
    },
    {
        "time": "2017-05-20T22:31:50.3369265Z",
        "score": 0,
        "comment": "Th-th-th-th-That's all, folks!  ",
        "handle": "@porkypig"
    },
    {
        "time": "2017-05-15T22:31:50.3369265Z",
        "score": 3,
        "comment": "Be very, very quiet! ",
        "handle": "@ElmerFudd"
    },
    {
        "time": "2017-04-16T22:31:50.3369265Z",
        "score": 0,
        "comment": "What's up, doc? ",
        "handle": "@bugsbunny"
    },
    {
        "time": "2017-04-18T22:31:50.3369265Z",
        "score": 3,
        "comment": "You're deth-picable!",
        "handle ": "@daffyduck"
    }
]

and Below is my HTML code

<script type="text/javascript" src="jquery-3.2.1.min.js"></script>

<div id="label"></div>
<script type="text/javascript">
    $.ajax({
        url: 'document.json',
        dataType: 'json',
        type: 'get',
        cache: false,
        success: function (data) {
            $(data).each(function (index, value) {
                console.log(value);
                $("#label").append(value.score);
            });
        }
    });
</script>

With the above code i am getting the all the scores in my div with id="label". Output="00303"

What if i want the score of third object from the object array in JSON? i.e only "3"

Upvotes: -1

Views: 46

Answers (1)

Dalin Huang
Dalin Huang

Reputation: 11342

two options.

1st, use data[2].score

2nd, inside your each, check the index, example:

            if(index === 2){
              $("#label").append(value.score);
            }

Option 1: Using data[2].score:

var data = [
    {
        "time": "2017-04-11T22:31:50.3369265Z",
        "score": 0,
        "comment": "Meep meep!  ",
        "handle": "@roadrunner"
    },
    {
        "time": "2017-05-20T22:31:50.3369265Z",
        "score": 0,
        "comment": "Th-th-th-th-That's all, folks!  ",
        "handle": "@porkypig"
    },
    {
        "time": "2017-05-15T22:31:50.3369265Z",
        "score": 3,
        "comment": "Be very, very quiet! ",
        "handle": "@ElmerFudd"
    },
    {
        "time": "2017-04-16T22:31:50.3369265Z",
        "score": 0,
        "comment": "What's up, doc? ",
        "handle": "@bugsbunny"
    },
    {
        "time": "2017-04-18T22:31:50.3369265Z",
        "score": 3,
        "comment": "You're deth-picable!",
        "handle ": "@daffyduck"
    }
]

console.log('3rd score: ' + data[2].score);

Upvotes: 1

Related Questions