Max Max - 2 months ago 6
Javascript Question

How can I return an Index location for an item in a JSON array by searching with text?

Here is my JSON array:

var planets = [{
"Name": "Mercury",
"Temperature": "427°C",
"Position" : 1
}, {
"Name": "Venus",
"Temperature": "462°C",
"Position" : 2

}, {
"Name": "Earth",
"Temperature": "16°C",
"Position" : 3
}]


Using the text "Earth" is there a method that would return me the index location of the item Earth in my Planets array?

For example:

planets.find("Earth")

Answer

Try this:

var index = -1;
var val = 'Earth';
var filteredObj = planets.find(function(item, i){
  if(item.Name === val){
    index = i;
    return i;
  }
});

console.log(index, filteredObj);
Comments