在Javascript中从JSON数组中查找名称/值对的有效方法 [英] Efficient way to find name value pairs from JSON array in Javascript

查看:85
本文介绍了在Javascript中从JSON数组中查找名称/值对的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在调用服务,该服务将响应作为具有名称/值对的对象数组发送.下面是一个示例.这些名称值对可以按任意顺序排列,但我只想访问名称"name2"的值.除了遍历每个对象并检查名称以获得name2的对应值之外,还有其他有效的方法吗?

I am currently making a call to a service which sends a response as an array of objects with name value pairs. An example of this can be seen below. There could be any amount of these name value pairs in any order but I just want to access the value for the name "name2". Is there an efficient way other than looping through each object and checking the name to obtain the corresponding value for name2?

[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}] 

因此,从以上数据集中,我希望找到一种有效的方法来搜索name2并获取相应的值"value2".

So from the above data set I would want an efficient way to search for name2 and get the corresponding value "value2".

谢谢

推荐答案

除非您知道名称为name2的对象的特定索引.

Unless you know the specific index of the object with the name name2 no.

您需要进行迭代,直到找到该名称,然后您才可以纾困.

You'll need to iterate until you find that name then you can bail out.

例如

var jsonData = [{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}];
for(var i=0;i<jsonData.length;i++){
  if(jsonData[i]['name'] == 'name2'){
    console.log('The value is: ' + jsonData[i]['value']);
    break;
  }
}

请注意,如果不需要支持Internet Explorer,则可以使用

Note that if you don't need to support Internet Explorer, you can use the Array.find() method to simplify this.

这篇关于在Javascript中从JSON数组中查找名称/值对的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆