skip to Main Content

I have a JSON file that has:
{ "a": "letter a", "b": "letter b", "c": "letter c" }

When the user type in the textbox "b", how do I convert the string from the textbox into a key to access the "b" key in the JSON in JS?

3

Answers


  1. How about accessing the value from the user first and then accessing the value from object.

     function myFunction() {
      var obj = { "a": "letter a", "b": "letter b", "c": "letter c" };
      var userInput = document.getElementById("user-input").value;
      if(userInput){
      console.log(obj[userInput] ?? "not found");
      }
    }
    Enter value: <input type="text" id ="user-input" onkeyup="myFunction()">
    Login or Signup to reply.
  2. You can use the square bracket notation to access the value of a specific key in a JSON object in JavaScript:

    var value = jsonObject['userInput'];
    

    For example:

    const jsonObject = JSON.parse('{ "a": "letter a", "b": "letter b", "c": "letter c" }');    
    
    var userInput = document.getElementById("textbox").value; // userInput = 'b'
    
    var value = jsonObject[userInput];
    
    console.log(value); // 'letter b'
    
    Login or Signup to reply.
  3. Here’s the solution for a given problem:

    App Structure:

    enter image description here

    app.js file

    const textBox = document.getElementById("textbox");
    const valueBox = document.getElementById("valuebox");
    let data;
    async function main() {
      await fetch("/data.json").then(async (v) => {
        data = await v.json();
      });
      console.log(data);
    }
    textBox.addEventListener("change", () => {
      let k = textBox.value;
      valueBox.innerHTML = data[k];
    });
    main();
    

    index.html file

    
        <!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>Document</title>
          </head>
          <body>
            <input id="textbox" />
            <div id="valuebox"></div>
          </body>
          <script src="./app.js"></script>
        </html>
    
    

    data.json file

    { "a": "letter a", "b": "letter b", "c": "letter c" }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search