Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 331
John Avatar asked Nov 27 '25 22:11

John


2 Answers

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);
like image 109
Ionică Bizău Avatar answered Nov 30 '25 11:11

Ionică Bizău


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.

like image 40
Jamiec Avatar answered Nov 30 '25 13:11

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!