Skip to content
Advertisement

How can I get the index from a JSON object with value?

This is my JSON string.

[{
    "name": "placeHolder",
    "section": "right"
}, {
    "name": "Overview",
    "section": "left"
}, {
    "name": "ByFunction",
    "section": "left"
}, {
    "name": "Time",
    "section": "left"
}, {
    "name": "allFit",
    "section": "left"
}, {
    "name": "allbMatches",
    "section": "left"
}, {
    "name": "allOffers",
    "section": "left"
}, {
    "name": "allInterests",
    "section": "left"
}, {
    "name": "allResponses",
    "section": "left"
}, {
    "name": "divChanged",
    "section": "right"
}]

Now, I have the value allInterests and I want to find out the index (this case; it is ‘7’) of this object in the above string. I tried the following code, but it always returns -1.

var q = MY_JSON_STRING
console.log(q.indexOf( 'allInterests' ) );

Advertisement

Answer

You will have to use Array.find or Array.filter or Array.forEach.

Since your value is array and you need the position of the element, you will have to iterate over it.

Array.find

var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var index = -1;
var val = "allInterests"
var filteredObj = data.find(function(item, i){
  if(item.name === val){
    index = i;
    return i;
  }
});

console.log(index, filteredObj);

Array.findIndex() @Ted Hopp‘s suggestion

var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];

var val = "allInterests"
var index = data.findIndex(function(item, i){
  return item.name === val
});

console.log(index);

Default Array.indexOf() will match searchValue to current element and not its properties. You can refer Array.indexOf – polyfill on MDN

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement