John
John

Reputation: 1751

Javascript JSON get index of value

I have JSON format:

{ device: 'eth0',
      Rx: { bytes: '491539402315', packets: '278178082' },
      Tx: { bytes: '15113860013', packets: '67405143' } }
{ device: 'lo',
      Rx: { bytes: '1653376107', packets: '6380792' },
      Tx: { bytes: '1653376107', packets: '6380792' } }

I need to get index of device value so that i can later extract bytes and packets...i have in database value eth0 so i need to get index 0 (if i put lo i need to get index 1)

In javascript how can i do that?

Upvotes: 3

Views: 3389

Answers (2)

Ionică Bizău
Ionică Bizău

Reputation: 113375

Assuming that's an array you can simply iterate the array:

var devices = [{ device: 'eth0',
      Rx: { bytes: '491539402315', packets: '278178082' },
      Tx: { bytes: '15113860013', packets: '67405143' } },
{ device: 'lo',
      Rx: { bytes: '1653376107', packets: '6380792' },
      Tx: { bytes: '1653376107', packets: '6380792' } }]
      
 function getIndex (name) {
   for (var i = 0; i < devices.length; ++i) {
    if (devices[i].device === name) {
      return i;
    }
   }
   return -1;
 }
 
console.log(getIndex("eth0"));
console.log(getIndex("lo"));
console.log(getIndex("missing device"));

Another slower approach, would be to use the map and indexOf functions:

var index = devices.map(c => c.device).indexOf(name);

Alternatively, findIndex, as Jaimec suggested, can be useful. If your are really concerned about the performance, you probably want to use the for loop version. Probably it doesn't matter that much in this context.

var index = devices.findIndex(c => c.device === name);

Upvotes: 2

Jamiec
Jamiec

Reputation: 136114

this is a job for findIndex!

var devices = [{ device: 'eth0',
      Rx: { bytes: '491539402315', packets: '278178082' },
      Tx: { bytes: '15113860013', packets: '67405143' } },
{ device: 'lo',
      Rx: { bytes: '1653376107', packets: '6380792' },
      Tx: { bytes: '1653376107', packets: '6380792' } }]
      
      
var idx = devices.findIndex(function(e) { return e.device == "eth0"} );
console.log(idx);

Note that findIndex is not supported by IE. If you follow the link above there is a perfectly good polyfill to add support to unsupported browsers.

Upvotes: 1

Related Questions