简体   繁体   English

JSON / Javascript:返回哪个数组对象包含某个属性

[英]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.

相关问题 JSON / Javascript:返回包含某个属性的数组对象的INDEX - JSON/Javascript: return INDEX of array object containing a certain property 在 JavaScript 中检查数组是否包含具有特定属性值的对象? - Check if an array contains an object with a certain property value in JavaScript? JSON object 返回包含键及其值的对象数组 - JSON object return of an array of objects which contains the keys and its values 使用javascript获取属性包含数组的对象作为值 - get the object which property contains an array as the value using javascript 如何在 Javascript 的数组中返回仅包含某个 object 的对象数组? - How do I return an array of objects that only contains a certain object in an array for Javascript? 将包含数组的对象插入返回JSON - inserting Object that contains array into return JSON Javascript按包含搜索词的标签子数组过滤或减少每个JSON对象 - Javascript Filter or Reduce each JSON object by child array of tags which contains search word 获取具有属性的数组中的对象,该属性是包含匹配值的数组 - Get an Object in an Array that has a property which is an Array that contains a matching value 递归删除嵌套json对象中包含空数组的对象 - Recursively remove object which contains empty array in nest json object 无法访问Javascript中对象属性的数组 - Failing accessing array which is property of an object in Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM