Skip to content
Advertisement

Search value in JSON and return to console

I am trying to search a value in a JSON file using a input field from the user through the browser.

A sample JSON object from the array of objects looks like this:

enter image description here

I have an event listener to wait for click from the user. After the user clicks the function will go to the api json site and retrieve all the data.

Next I would like to search through that JSON data for what the user typed in.

Example:

enter image description here

user input: “Cannonball”

expected output: 196 (buy_average)

However I am unable to figure out how to search through the object array.

Here’s what I got:

the parameter “data” is the JSON objects that was retrieved from API. I know that works properly because I’m able to display it in the console.

function renderHTML(data) {
  var searchVal = document.getElementById("search").value;
  console.log(searchVal);
  for (i=0; i<data.length; i++) {
    if (data["i"].name == searchVal) {
      console.log(data["i"].buy_average);
    }
  }
};

As of right now I’m just trying to figure how to look through an object array after retrieving it from the web and display it to the console.

When I click on the button nothing in the console appears to be happening except for the user’s input. How can I fix this?

Advertisement

Answer

If data is an object, the length property will give you undefined. You can get the values using Object.values() and then iterate over the properties.

let data = {
    0:{        id:0,name:"aa"    },
    1:{        id:1,name:"Cannonball"},
    2:{        id:2,name:"xx"    },
};

let searchVal = "Cannonball";
Object.values(data).forEach(e=>{
   if(e.name === searchVal){
       console.log("This is the object: ");
       console.log(e);
   }
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement