我有这样的集合......
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);
是否可以为doc_count
属性为key
的对象获取属性ia-Business
的值?
答案 0 :(得分:3)
使用Array#find,如
buckets.find(bucket => bucket.key === 'ia-Business')
答案 1 :(得分:1)
现在,buckets
基本上是一个带有额外步骤的对象。删除这些额外步骤将允许您通过密钥直接访问您的条目:
const onJSON = { buckets: {
"ia-Business": 88,
"ia-Health_Sciences_and_Allied_Health": 58
// ...
}};
或者,如果您预计需要存储的数量超过文档计数,则此方法将更具可扩展性:
const onJSON = { buckets: {
"ia-Business": { doc_count: 88 },
"ia-Health_Sciences_and_Allied_Health": { doc_count: 58 }
// ...
}};
答案 2 :(得分:1)
您的存储桶属性包含一个数组,而javascript不允许您通过属性值轻松访问数组中的对象。
您需要遍历对象数组以找到您正在寻找的bucket
,例如:
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);
或者,您可以使用underscore
方法使用javascript findWhere
库:
var desiredBucket = _.findWhere(data.buckets, { key: 'ia-Business' });
它搜索由数组中对象的属性匹配的数组,并返回第一个结果。