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

11,129

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

Solution 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.

Share:
11,129
gladtobegrey
Author by

gladtobegrey

Amateur

Updated on June 19, 2022

Comments

  • gladtobegrey
    gladtobegrey almost 2 years

    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.

  • gladtobegrey
    gladtobegrey almost 13 years
    Thanks, constructive and helpful.
  • gladtobegrey
    gladtobegrey almost 13 years
    Thanks, also very helpful; I note your loop contains "var i=0, L=arr.length" - presumably to save re-evaluating arr.length on every iteration? I hadn't thought of doing that.