Search code examples
javascriptjsoncolorssetting

Getting 3rd object from json array


I have an array in json that looks like this:

[ 
  {"x":161,"y":109,"colour":"FF0000"},
  {"x":146,"y":93, "colour":"FF0000"},
  {"x":133,"y":81, "colour":"FF0000"} 
];

I want to set a strokeStyle property to get a colour from the objects given.

So how can I select the "colour" value?


Solution

  • JavaScript lets you access attributes in JSON objects pretty easily. For example, you could iterate through this particular object and console.log() out the colour with this loop (assuming jsonObj is the variable storing the given JSON array):

    for (var i = 0; i < jsonObj.length; i++){
        console.log(jsonObj[i].colour);
    }
    

    (If you weren't looking to iterate through them, and just wanted a specific object, you could just use a numerical index instead of an iterator with a loop.)

    Here's a JSFiddle example. (Remember to open the console log in order to see the results.)

    If this isn't what you were looking for, feel free to let me know and I'll be happy to help further. Good luck!