Javascript - get the value of a property within a

2019-04-30 07:15发布

问题:

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
     ]
}

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

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?

Thanks.

回答1:

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

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

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.

Example:

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

The retrieval of the object would be O(1) and as simple as obj["valueB2"]



回答2:

There isn't a more elegant way to do this. The only thing you know without looping are the indexes. That's not the identifier you want, so you'll have to inspect the content: loop:

function byKey(arr, key) {
  for ( var i=0, L=arr.length; i<L; i++ ) {
    if ( arr[i].key1 === key ) {
      return arr[i];
    }
  }
}

Or something like that.



回答3:

To round off: taking ideas from both answers, I adopted this simpler JSON structure:

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

with the suggested loop function to find the element for "key2:"valueB2" - the array is accessed by index for most of the time, and only occasionally by the loop-search, so that seemed the best balance. I also realised I could do away with the containing object "map" as it wasn't adding any utility.