Ad

Linear Searching In A JavaScript Object

- 1 answer

I'm attempting to create a bunch of JS objects and place them all into an array to be able to linear search for values contained within each of them.

I'm fairly certain the problem is coming in the nested for loops while searching for the value passed in. I was looking into the .contains() method and just using the simple comparison operators == and === and none of them had been working for me. So my issue is when I type into my text box 'times square', for the time being I just want the alert box to pop up and show the name of the object which contains that destination in its POI array.

My HTML below is just a simple text box and a submit button. Any help?

// scripts

var bmtBroadWayLine = {
      color: 'yellow',
      poi: ["times square", 'south ferry'],
      letters: 'N Q R',
      name: "BMT Broadway Line",
};

var destinations = [];
destinations[1] = bmtBroadWayLine;

function findDestination() {
      for (var i = 0; i < destinations.length; i++) {
            for (var j = 0; j < destinations[i].poi.length; j++) {
                  if (destinations[i].poi[j] == document.getElementById("dest-entry")) {
                        alert(destinations[i].poi[j].name);
                  }
            }
      }
}
<!DOCTYPE html>
<html>
      <head>
            <meta charset="utf-8">
            <title>Routes</title>
      </head>
      <body>

            <h1>Where Do You Want To Go?</h1>

            <input type="text" id="dest-entry">
            <input type="button" value="Send" onclick="findDestination()">

            <div id="output"></div>

            <script src="scripts.js"></script>
      </body>
</html>

Ad

Answer

There are many things wrong with this script:

  • You're comparing string to DOM object
  • You're trying to access name property of a string
  • You're using a 1-based index in a zero-based index language

not error but still:

  • you're not verifying for null
  • you're looking up a DOM item on each iteration, which is slow.

You're comparing a string with a DOM object.

if (destinations[i].poi[j] == document.getElementById("dest-entry")) {
    alert(destinations[i].poi[j].name);
}

Instead, compare it with the string value inside that DOM object:

if (destinations[i].poi[j] == document.getElementById("dest-entry").value) {
    alert(destinations[i].poi[j].name);
}

Might also want to check for NULL for this document.getElementById("dest-entry")

Also, you're accessing the name property of a string

alert(destinations[i].poi[j].name);

you probably just want this:

alert(destinations[i].name);

Also:

destinations[1] = bmtBroadWayLine;

Simply do

destinations.push(bmtBroadWayLine);

When you add an item with an index that's not the first available, the length increases by more than 1. So now you have 1 element, length is 2 however, and the first element is undefined, and you're trying to access properties of undefined.

Ad
source: stackoverflow.com
Ad