1

This is my app.js file

$(document).ready(function () {
        $.getJSON("http://localhost:3000/db.json", function (data) {

        $(data.as).each(function (index, value) {

            console.log(value);
        });
    });
});

and this is db.json file

{
  "as": [
    {
      "imageID": "1",
      "imageSource": "Popular Science 1",
      "alt": "Science 1"
    },
    {
      "imageID": "2",
      "imageSource": "Popular Science 2",
      "alt": "Science 2"
    }
  ]
}

How to get only, for example, Popular Science 2? if I write console.log(value[1]);, an error is displayed. How to index an array?

1
  • In JavaScript and most programming languages, arrays are accessed by zero based indices. [0] for the first item, [1] for the second, etc Commented Jun 12, 2020 at 10:29

1 Answer 1

1

You can simply use:

value.imageSource

as value is the object here.

const data = {as:[{imageID:"1",imageSource:"Popular Science 1",alt:"Science 1"},{imageID:"2",imageSource:"Popular Science 2",alt:"Science 2"}]};

$(data.as).each(function(index, value) {
  console.log(value.imageSource);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


If you only want Popular Science 2, then there is no need to loop. You can simply do:

const data = {as:[{imageID:"1",imageSource:"Popular Science 1",alt:"Science 1"},{imageID:"2",imageSource:"Popular Science 2",alt:"Science 2"}]};

console.log( data.as[1].imageSource );

Or, with some validation like:

const data = {as:[{imageID:"1",imageSource:"Popular Science 1",alt:"Science 1"},{imageID:"2",imageSource:"Popular Science 2",alt:"Science 2"}]};

// Vlidating that we actually have an array and data as index 1
if( data && data.as && data.as.length > 1){ 
  console.log( data.as[1].imageSource );
}

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but I only want to show 'Popular Science 2'? How?
You can use console.log( data.as[1].imageSource ); or console.log( data?.as[1]?.imageSource );

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.