How to use prompt input to loop through an array of objects and display a property

1.7k Views Asked by At

First thank you in advance for any responses to this problem I am having. I am new to JS and feel that this code should be pretty straight forward, but it is not working as intended.

I want to search through these objects in the array by name, and if the name (that is obtained through the prompt) is found in the array, I want to display the id of that object.

if I type 'Jef' into the prompt, I get the ID; but if I type 'Steve' or 'Ryan' I get nothing. I also noticed that the loop seems to end no matter what I type without a break being added. I think the loop is breaking, but I don't know what is causing it to break before the 'If' condition is met. Please help!

var array = [{
    name: 'Jef',
    age: 29,
    id: '000'
  }, {
    name: 'Steve',
    age: 28,
    id: '001'
  },
  {
    name: 'Ryan',
    age: 28,
    id: '002'
  }
];

var i;

for (i = 0; i < array.length; i++) {
  if (prompt() == array[i].name) {
    console.log(array[i].id)
  }
}

2

There are 2 best solutions below

1
Jacob Gaiski On

Try this. You need to sort through your array and perform a strong match, then return the ID.

function NameExists(strName,objectArray)
{
    //convert to lower for type sensitive
    strName = strName.toLowerCase();
    for(var i = 0; i <objectArray.length; i++)
    {
        //convert to lower for type sensitive
        var comparison = objectArray[i].Name.toLowerCase();

        if(comparison.match(strName)==comparison)
            return objectArray[i].id;
    }
}
0
Andrew Lohr On

The way you are doing it is close. You just need to put the prompt() outside the loop. Once you have the input to search, you then loop through your whole array of objects.

For example:

var nameInput = prompt();
for (i =0; i < array.length; i++){
    if (nameInput == array[i].name) {
       console.log(array[i].id)
    }
}

Small explanation

Since your prompt is in a loop that also loops your array of objects, there can only be 1 "correct" answer at that given prompt point - whatever index (array[i].name) the loop is currently on.

To see more of what I mean run your current code and type jef the first time the prompt comes up, Steve the second time, and Ryan the third time- this way gets your IDs, but is probably not your intended outcome.