Sometimes, we want to get the index from a JSON object with value with JavaScript.
In this article, we’ll look at how to get the index from a JSON object with value with JavaScript.
How to get the index from a JSON object with value with JavaScript?
To get the index from a JSON object with value with JavaScript, we can use the array findIndex method.
For instance, we write:
const data = [{
  "name": "allFit",
  "section": "left"
}, {
  "name": "allbMatches",
  "section": "left"
}, {
  "name": "allOffers",
  "section": "left"
}, {
  "name": "allInterests",
  "section": "left"
}, {
  "name": "allResponses",
  "section": "left"
}, {
  "name": "divChanged",
  "section": "right"
}];
const val = "allInterests"
const index = data.findIndex((item) => {
  return item.name === val
});
console.log(index);
to call data.findIndex with a callback that finds the first item where the name property of an object in data is equal to val and returns the index of that object.
Therefore, index is 3 since the 4th object in data has name set to 'allInterests'.
Conclusion
To get the index from a JSON object with value with JavaScript, we can use the array findIndex method.
