0

I have a collection like this ...

var data = {
    "buckets": [
        {
            "key": "ia-Business",
            "doc_count": 88
        },
        {
            "key": "ia-Health_Sciences_and_Allied_Health",
            "doc_count": 58
        },
        {
            "key": "ia-Media_Communications_and_Creative_Arts",
            "doc_count": 40
        },
        {
            "key": "ia-Information_Technology",
            "doc_count": 35
        }
    ]
};


alert(data.buckets[0].doc_count);

Is it possible to fetch the value of property doc_count for the object with key property of ia-Business?

Slyper
  • 896
  • 2
  • 15
  • 32

3 Answers3

3

Use Array#find, as in

buckets.find(bucket => bucket.key === 'ia-Business')
1

Right now, buckets is basically an Object with extra steps. Removing those extra steps will allow you to access your entries directly by key:

const onJSON = { buckets: {
    "ia-Business": 88,
    "ia-Health_Sciences_and_Allied_Health": 58
    // ...
}};

Or, if you anticipate needing to store more than the doc count, this approach will be a little more extensible:

 const onJSON = { buckets: {
    "ia-Business": { doc_count: 88 },
    "ia-Health_Sciences_and_Allied_Health": { doc_count: 58 }
    // ...
}};
wbadart
  • 2,583
  • 1
  • 13
  • 27
1

Your buckets property contains an array, and javascript doesn't allow you to easily access an object in an array by a property value.

You'll need to iterate over the objects array to find the bucket you're looking for, for example:

var desiredBucket;

for (var i = 0; i < data.buckets.length; i++) {
    var bucket = data.buckets[i];
    if (bucket.key === 'ia-Business') {
        desiredBucket = bucket;
        break;
    }
}

console.log(desiredBucket.doc_count);

Alternatively, you could use the javascript underscore library, using the findWhere method:

var desiredBucket = _.findWhere(data.buckets, { key: 'ia-Business' });

It searches an array matching by a properties on objects within the array, and returns the first result.

Sneaksta
  • 1,041
  • 4
  • 24
  • 46