Question

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?

Was it helpful?

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!

OTHER TIPS

You can use this:

//data is your array
$.each(data, function(index, element) {
    // use can access the colour field like this:
    console.log(element.colour); 
});

1. Use foreach

data.forEach(function(entry) {
    console.log(entry.colour);
});

2. For loop

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

3. Use for-in

for (entry in data) {
    console.log(entry.colour);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top