0

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

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;

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?

3
  • 1
    .filter() Commented Jul 31, 2015 at 13:08
  • What kind of parser produces this Json? Commented Jul 31, 2015 at 13:18
  • not sure. It is a proprietary API. Is there something wrong with it? Commented Aug 1, 2015 at 13:20

1 Answer 1

1

Use Array.prototype.filter:

var numberValue, list = parsed.something.terms.filter(function(a){
  return a.label==='number';
});
numberValue = list.length ? list[0].value : -1;
Sign up to request clarification or add additional context in comments.

3 Comments

However, with find you can't to get all value elements, if need.
Thank you for this. How would I modify this code to return the array index of the "term" where the "label" = "number"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.