简体   繁体   English

Javascript JSON获取值索引

[英]Javascript JSON get index of value

I have JSON format: 我有JSON格式:

{ 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) 我需要获取设备值的索引,以便以后可以提取字节和数据包...我在数据库值eth0中具有索引,所以我需要获取索引0(如果我放入lo则需要获取索引1)

In javascript how can i do that? 在JavaScript中我该怎么做?

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: 另一种较慢的方法是使用mapindexOf函数:

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

Alternatively, findIndex , as Jaimec suggested, can be useful. 另外,如Jaimec建议的findIndex ,findIndex可能会有用。 If your are really concerned about the performance, you probably want to use the for loop version. 如果您确实关心性能,则可能要使用for循环版本。 Probably it doesn't matter that much in this context. 在这种情况下,可能无关紧要。

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

this is a job for findIndex ! 这是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. 请注意,IE不支持findIndex If you follow the link above there is a perfectly good polyfill to add support to unsupported browsers. 如果您点击上面的链接,则可以使用非常好的polyfill向不受支持的浏览器添加支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM