dtburgess dtburgess - 23 days ago 6
Javascript Question

JSON/Javascript: return INDEX of array object containing a certain property

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 asked a question about parsing the object out where label: number here:
JSON/Javascript: return which array object contains a certain property

I got a sufficient answer there (use filter()), but now need to know the original index of the object.

This issue seems to have the answer, but I simply don't know enough about javascript to translate it into something useful for my particular problem.

The following code successfully returns the object. Now I need to modify this to return the original index of the object:

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


This needs to be a pure javascript solution, no external libraries, etc.

Answer

I don't think you can modify the filter solution as within the filter you've lost the indexes.

The solution you've linked to uses the angular external library.

So here is a pure JS solution:

var numberValue = parsed.something.terms
    .map(function(d){ return d['label']; })
    .indexOf('number');

Array.prototype.indexOf()

Array.prototype.map()

Comments