使用Javascript - 获得其密钥的特定JSON数组元素中的一个属性的值 [英] Javascript - get the value of a property within a specific JSON array element by its key

查看:89
本文介绍了使用Javascript - 获得其密钥的特定JSON数组元素中的一个属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON结构是这样的:

I have a JSON structure like this:

{
map: [
      {"key1":"valueA1", "key2":"valueA2", "key3":"valueA3"},
      {"key1":"valueB1", "key2":"valueB2", "key3":"valueB3"},
      {"key1":"valueC1", "key2":"valueC2", "key3":"valueC3"},
       .... etc
     ]
}

...我加载到我的JavaScript应用程序通过JSON.parse成为一个对象()。

... which I load into my javascript app to become an object via JSON.parse().

我想从对象数组的元素检索(说)KEY3的值,其中键2 ='valueB2'。

I want to retrieve (say) the value of key3 from the element of the object array where key2='valueB2'.

我可以通过循环做,但不知道是否有一个更优雅(例如单线和更有效的)这样的方式,而不必知道为数组元素的索引号

I can do it by looping through, but wondered if there was a more elegant (e.g. single line and more efficient) way of doing this, without having to know the index number for the array element?

我有网站谷歌的负载,收效甚微。或者,我会更好,简化/支持对象的简单列表去除数组?

I've google loads of sites, to little avail. Or would I be better simplifying/removing the array in favour of a simple list of objects?

感谢。

推荐答案

JSON通常有双引号周围的所有键和值除号。

JSON will usually have double quotations " around all keys and values except for numbers.

不过环是你最有效和最好的选择。有新的功能数组的迭代方法,但仅适用于新的JS引擎和浏览器,他们可以在这里找到:的 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

However loop is the most efficient and best choice you have. There is new functional array iteration methods, but only available on new JS engines and browsers, they can be found here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

如果你有改变JSON结构的自由,你应该实现它是一个对象,而不是对象的数组,其中最关键的是KEY2的值和值是对象。

If you have the liberty of changing the JSON structure, you should implement it to be an Object instead of an array of objects where the key is the value of key2 and the value is the Object.

例如:

{
    "valueB2": {
        "key1": "valueB1",
        "key2": "valueB2",
        "key3": "valueB3"
    }
}

对象的检索是O(1)和的obj [valueB2]

这篇关于使用Javascript - 获得其密钥的特定JSON数组元素中的一个属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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