Want to know how to input objects in an array

28 Views Asked by At

i want to loop through an array and after looping through the array I should be able to select an item from the array with an input function

I tried using the for loop and if statements to call a variable from the array it didn’t work. I wanted to use the if statement as an input to help select an item from the array after looping

3

There are 3 best solutions below

0
Arcadian Child On

The answer can change depending on the language you are using, be sure to specify that give sample code. I do usually loop if statements in Java and it works. You sure you don't have a tipo in your code?

In Javascript you can use the array.filter() function to filter the array to the condition you are specifying:

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

Hope this answers your question.

0
Codin Plus On

This is the HTML code in going to use input to illustrate.

<input type="text" id="input"/>
<p></p>

This is the real JavaScript code.

    <script>
  let input = document.querySelector("#input");
  let p = document.querySelector("p");
      let arr  = ["school","bag","shoe"];
      input.onkeyup = function(){
      let result = arr.filter(e=>{
        if(input.value == e){
          
          return e;
        }
      }).join("");
          console.log(result)
  p.innerHTML = result;
      }
        </script>

Hope it ask your question vote-up if it work

0
Codin Plus On

Now if the array contain objects you can loop through the objects by the object name example.

  <input type="text" id="input"/>
<p></p>

<script>
let input = document.querySelector("#input");
    let p = document.querySelector("p");
// do this if the array are objects
    let arr  = [{name:"paul",color:"red"},{name:"peter",color:"blue"},{name:"joe",color:"green"},{name:"john",color:"yellow"}];


let status = "";
input.onkeyup = function() {
  let result = arr.filter(e => { 


if (input.value == e.name || input.value == e.color) {
return e;
    }
  }).map(e=>{


return e;
  });



let name = (typeof result[0].name == "undefined")?"":result[0].name;
  let color = (typeof result[0].color == "undefined")?"":result[0].color;
  console.log(result)
  p.innerHTML = name, color;
}
</script>