AppleBud
AppleBud

Reputation: 1541

How to read objects in JSON format & compare it to a user entered input?

I am trying to make an application in which certain values are stored in JSON format and i want to access these values using indexes rather than hard coding it. My HTML file along with javascript is:

<html>
<head>
    <title> My Dictionary </title>
    <script type="text/javascript">

    function search(){
        var myDictionary = 
        {"Apple": 
           {"Meaning": "Fruit", "Category": "Sweet", "Pronounciation": "Apple"} 
           ,
        "Apples":
           {"Meaning": "Fruit", "Category": "Sweet", "Pronounciation": "Apple"}}
        };

        var v= document.getElementById("search").value;
    }
    </script>    
</head>          
<body>           
    Enter your Text: <input type="text" id="search" name="search"  />
    <input type="button" value="search" onclick="search();" />

</body>
</html>

I want to compare the user entered value with the data in the JSON format. For eg. if user entered "Apples", then how can I check this with the values in the array?

Upvotes: 2

Views: 770

Answers (1)

asifrc
asifrc

Reputation: 5841

I'm not sure if this is the most efficient way to do this, but it is one way: you can loop through the myDictionary array and check if the property v exists using a combination of typeof and bracket notation. Here's an example:

var result;
for (var i=0; i<myDictionary.length; i++)
{
    if (typeof myDictionary[i][v] === "object")
    {
        result = myDictionary[i];
        break;
    }
}

I copied your myDictionary object into my console, set v to "Apple", ran my code, and result successfully contained the Apple object. It's important to note that JavaScript variables/properties are case-sensitive, so if the user types in "apple" instead of "Apple", you won't get a result. The easiest way manage this is to make sure all your dictionary keywords are lowercase, and use v.toLowerCase().

Let me know what you think, or if you have any questions :)

Upvotes: 1

Related Questions