[英]JSON/Javascript: return which array object contains a certain property
Given a JSON object such as this: 给定这样的JSON对象:
{
"something": {
"terms": [
{
"span": [
15,
16
],
"value": ":",
"label": "separator"
},
{
"span": [
16,
20
],
"value": "12.5",
"label": "number"
}
],
"span": [
15,
20
],
"weight": 0.005,
"value": ":12.5"
}
I would like write some javascript that would determine the index of the "term" that has a "label": "number". 我想写一些JavaScript来确定具有“标签”:“数字”的“项”的索引。 Ultimately I want to determine the "value" of the "term" that has a "label": "number", I know I can get that with something like this, where the index is known: 最终,我想确定具有“标签”:“数字”的“项”的“值”,我知道我可以用类似这样的东西来获得索引已知的地方:
parsed = JSON.parse(result.trim());
var numberValue = parsed.terms[1].value;
My first thought is perhaps to just write a foreach loop and then return the numberValue when I arrive at an array object that has "label": "number". 我的第一个想法可能只是编写一个foreach循环,然后在到达具有“标签”:“数字”的数组对象时返回numberValue。
Is there a more elegant and/or concise way to do this? 有没有更优雅和/或更简洁的方式来做到这一点?
Use Array.prototype.filter
: 使用Array.prototype.filter
:
var numberValue, list = parsed.something.terms.filter(function(a){
return a.label==='number';
});
numberValue = list.length ? list[0].value : -1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.