Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - get the value of a property within a specific JSON array element by its key

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.

like image 471
gladtobegrey Avatar asked Oct 11 '22 03:10

gladtobegrey


2 Answers

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

like image 137
Amjad Masad Avatar answered Oct 20 '22 06:10

Amjad Masad


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.

like image 26
Rudie Avatar answered Oct 20 '22 06:10

Rudie