Chef Tony
Chef Tony

Reputation: 475

How to find highest key in JSON?

An API I'm working with is returning poorly structured data like this:

{
    "scsi0": "vm-101-disk-1.qcow2,size=32G",
    "scsi1": "vm-101-disk-2.qcow2,size=32G",
    "scsi2": "vm-101-disk-3.qcow2,size=32G"
}

As you can see, instead of having a scsi object with then contains the 0, 1, 2 key/value pairs, I just have the keys named like that.

In JavaScript, how can I search for the highest scsi value which in that case would be 2?

Upvotes: 3

Views: 2056

Answers (3)

trincot
trincot

Reputation: 350127

You could use a collator to get a compare function that takes such embedded numbers into account:

const data = {
    "scsi0": "vm-101-disk-1.qcow2,size=32G",
    "scsi11": "vm-101-disk-2.qcow2,size=32G",
    "scsi2": "vm-101-disk-3.qcow2,size=32G"
};

const cmp = (new Intl.Collator(undefined, {numeric: true})).compare;
const max = Object.keys(data).reduce((a, b) => cmp(a, b) > 0 ? a : b);

console.log(max)

Upvotes: 2

Kosh
Kosh

Reputation: 18378

Use reduce on keys of your object:

var  o = {
    "scsi0": "vm-101-disk-1.qcow2,size=32G",
    "scsi11": "vm-101-disk-2.qcow2,size=32G",
    "scsi2": "vm-101-disk-3.qcow2,size=32G"
};


var max = Object.keys(o).reduce((m, k) => +m.replace(/\D/g, '') > +k.replace(/\D/g, '') ? m : m = k);

console.log(max, +max.replace(/\D/g, ''))

Upvotes: 1

sauntimo
sauntimo

Reputation: 1591

Object.keys() is a good place to start for jobs like this. How about something like this?

var data = {
  "scsi0": "vm-101-disk-1.qcow2,size=32G",
  "scsi1": "vm-101-disk-2.qcow2,size=32G",
  "scsi2": "vm-101-disk-3.qcow2,size=32G"
};

// get keys of data
var keys = Object.keys(data);

// get array of number values
var numbers = keys.map(function(key) {
  // strip text out of keys, parse as integers
  return parseInt(key.replace(/\D/g, '') || 0);
})

// get the largest number in the array
var highest = Math.max.apply(null, numbers);

// build the data key with this number
var key = "scsi" + highest;

// get the data pertaining to the key
var final = data[key];

// log the result
console.log(final);

Upvotes: 4

Related Questions