1

I have a nested Array which has two Arrays:

 var People = [
    {
      Name: "John",
      Age: "42",
    },
    {
      Name: "Peter",
      Age: "78",
    }
  ];

With an input field and a button I want to look now for the element, for example I type in "John" into the input field and click on the button. After that it should output the Array that has "John" in it.

How can I do that? And is it possible to output the Array to different input fields (name element and age element in two different input fields)?

Thank you very much!

Cyborg29
  • 63
  • 5

1 Answers1

1

Well, you can use the find method to look inside the array. it will return the first object which contains a person with the name entered in the input, or undefined in case a person with that name doesn't exist.

Note, that if you want to get multiple results (i.e, check for many john's, you can use the filter method which will return all of the people that have john as their name.

 var People = [
    {
      Name: "John",
      Age: "42",
    },
    {
      Name: "Peter",
      Age: "78",
    }
  ];
  
  function lookForName(){
  var name = document.getElementById('name').value
   const person =  People.find(x => x.Name === name);
   alert(person?.Name || "not found !")
   return false;
  }
<form onsubmit="return lookForName()">
  <label for="name">name: </label>
  <input type="text" id="name" name="name"><br>
  <input type="submit" value="Submit">
</form>
Ran Turner
  • 14,906
  • 5
  • 47
  • 53