1

From the following object, how can I get the 'air' reading from the property with largest index key i.e. 4? (30.9)

{
  1: {
    air: "31.2",
    evap: "25.3",
    t_condenser: "43.8"
  },
  2: {
    air: "31.1",
    evap: "25.3",
    t_condenser: "43.6"
  },
  3: {
    air: "31.0",
    evap: "25.3",
    t_condenser: "43.5"
  },
  4: {
    air: "30.9",
    evap: "25.2",
    t_condenser: "43.3"
  }
}

I have tried the following, to try to get the last key, but it just reads undefined:

$.getJSON("handler.php?action=fetchLAE", function(data){

  console.log(data.length);

});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
ldmo
  • 369
  • 1
  • 2
  • 9

3 Answers3

2

Note: The data is badly formatted. That is what an array is for, your API returns an Object.

Solution: find the highest key in data (which is an Object):

data[Object.keys(data).sort().pop()].air

Explanation:

Object.keys(data)

Get all the properties as an array e.g. [1,4,3,2].

Now we sort it ascending and take the last:

.sort().pop()

So we take this property out of the object, and take its air value:

data[4].air

http://jsbin.com/setibevozu/edit?console

James W.
  • 154
  • 3
  • 13
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

You can obtain the keys of the object with Object.keys() and then use Math.max to get the highest one.

var json = {
  1: {
    air: "31.2",
    evap: "25.3",
    t_condenser: "43.8"
  },
  2: {
    air: "31.1",
    evap: "25.3",
    t_condenser: "43.6"
  },
  3: {
    air: "31.0",
    evap: "25.3",
    t_condenser: "43.5"
  },
  4: {
    air: "30.9",
    evap: "25.2",
    t_condenser: "43.3"
  }
};


var maxKey = Math.max(...Object.keys(json));
var lastElementAir = json[maxKey].air;

console.log(lastElementAir);
nitobuendia
  • 1,228
  • 7
  • 18
  • 2
    Just a side note, this answer uses the spread operator which is only available in ES6+. Equivalent in ES5: `Math.max.apply(Math, +Object.keys(json))`. – Derek 朕會功夫 Apr 14 '17 at 16:25
1

This is not a valid JSON, but a javascript object.

You can make use of the Object.keys function to get the object properties and then get to the last element or property using the length property.

console.log(obj[Object.keys(obj).length].air);

var obj = {
1: {
air: "31.2",
evap: "25.3",
t_condenser: "43.8"
},
2: {
air: "31.1",
evap: "25.3",
t_condenser: "43.6"
},
3: {
air: "31.0",
evap: "25.3",
t_condenser: "43.5"
},
4: {
air: "30.9",
evap: "25.2",
t_condenser: "43.3"
}
};

console.log(obj[Object.keys(obj).length].air);
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41