Lukali
Lukali

Reputation: 343

How can i refer to specific element in JSON list?

I got the following profile, called leadfree.json. Inside it, I get the following:

{"type": "profile", "data": [[0, 25], [90, 150], [180, 183], [211, 237], [234, 184], [313, 26]], "name": "leadfree"}

In one of my function in a .js file, I got the following function:

ws_status.onmessage = function(e)
{
    x = JSON.parse(e.data)
    ...
    if (x.heat > 0.5) {//do something}   //example
    ...
}

I would like to refer to the [234,184]. Id like to say that if the data is right now whatever is in 5th block of data, id like to do something

if data = [x5,y5] do something.

How would I do that? I'm quite new to JSON and just trying to implement some changes to open-source web-application.

Here is my try:

if (x.[5]) {window.alert("!");}

The values will not stay constant, which is why I can't just use the values.

For now, I also can't test it, since it's linked to a hardware application, on Linux.

Upvotes: 2

Views: 1108

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Array in JS is 0 indexed so you need to use index 4 to get the info in position 5 like :

var e = JSON.parse('{"type": "profile", "data": [[0, 25], [90, 150], [180, 183], [211, 237], [234, 184], [313, 26]], "name": "leadfree"}');

console.log(e.data[4]); //result [234, 184]

Now when you get the array at the desired position you could perform the flow you want.

Upvotes: 2

Related Questions