从名称为JSON的数组中获取一项 [英] get one item from an array of name,value JSON

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

问题描述

我有这个数组:

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});

是否可以通过知道名称来获取值或特定元素?

is it possible to do get the value or a specific element by knowing the name ?

类似这样的东西:

arr['k2'].value

arr.get('k1')

推荐答案

通常通过数字索引访问数组,因此在您的示例arr[0] == {name:"k1", value:"abc"}中.如果您知道每个对象的name属性都是唯一的,则可以将它们存储在对象而不是数组中,如下所示:

Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the name property of each object will be unique you can store them in an object instead of an array, as follows:

var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";

alert(obj["k2"]); // displays "hi"

如果您实际上想要一个像帖子中那样的对象数组,则可以遍历该数组并在找到具有具有所需属性的对象的元素时返回:

If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

function findElement(arr, propName, propValue) {
  for (var i=0; i < arr.length; i++)
    if (arr[i][propName] == propValue)
      return arr[i];

  // will return undefined if not found; you could return a default instead
}

// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"

var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined

alert(findElement(arr, "name", "k2")["value"]); // displays "hi";

alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property

这篇关于从名称为JSON的数组中获取一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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