JSON / JavaScript的:返回的数组对象包含某种特性 [英] JSON/Javascript: return which array object contains a certain property

查看:136
本文介绍了JSON / JavaScript的:返回的数组对象包含某种特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于JSON对象像这样:

Given a JSON object such as this:

{
  "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"
  }

我想写一些JavaScript,将确定有一个标签的术语的指标:数字。最后,我要确定具有标签中的术语的价值:数字,我知道我能得到像这样的东西,这里的指数是已知的:

I would like write some javascript that would determine the index of the "term" that has a "label": "number". 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;

我首先想到的也许是只写一个foreach循环,然后返回numberValue当我有标签数组对象到:数字

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

有没有更优雅和/或简明的方式做到这一点?

Is there a more elegant and/or concise way to do this?

推荐答案

使用 Array.prototype.filter

var numberValue, list = parsed.something.terms.filter(function(a){
  return a.label==='number';
});
numberValue = list.length ? list[0].value : -1;

这篇关于JSON / JavaScript的:返回的数组对象包含某种特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆