-1

I want to retrieve the array value name under my onRegister function. But I don't think arrayFullNames.name is correct.

     var arrayFullNames = [
        {name: 'David', surname: 'Jones', age: 29},
        {name: 'Jack', surname: 'Sparrow', age: 33},
        {name: 'Monkey', surname: 'Idontknow', age: 9},
        {name: 'JavaScript' , surname: 'Something', age: '6 weeks'}
    ];

    function onRegister(){
      var userQuestion = prompt("What is your name", '');

    if(userQuestion == arrayFullNames.name){
      alert('name match');
     }else{
      alert('no match');
     }
  }
horcrux88
  • 333
  • 1
  • 5
  • 15
  • 1
    The first answer here might help: https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript – Tals Nov 17 '17 at 19:32

3 Answers3

1

You can use array#some

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

var arrayFullNames = [{ name: 'David', surname: 'Jones', age: 29 }, { name: 'Jack', surname: 'Sparrow', age: 33 }, { name: 'Monkey', surname: 'Idontknow', age: 9 }, { name: 'JavaScript', surname: 'Something', age: '6 weeks' } ];

function onRegister() {
  var userQuestion = prompt("What is your name", '');
  if (arrayFullNames.some(({name}) => name === userQuestion)) {
    alert('name match');
  } else {
    alert('no match');
  }
}
onRegister()
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

Arrays works based on indexes not like objects. Try the following

var arrayFullNames = [
    {name: 'David', surname: 'Jones', age: 29},
    {name: 'Jack', surname: 'Sparrow', age: 33},
    {name: 'Monkey', surname: 'Idontknow', age: 9},
    {name: 'JavaScript' , surname: 'Something', age: '6 weeks'}
];

function onRegister(){
  var userQuestion = prompt("What is your name", '');
  for(var i=0; i< arrayFullNames.length; i++){
    if(userQuestion == arrayFullNames[i].name){
      alert('name match');
      return true;
    }
  }
  alert('no match');
  return false;
}
anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62
0

You can use the array.indexOf function to solve this issue:

if (arrayFullNames.indexOf(function(obj) { 
  return userQuestion == obj.name;
}) > -1) {
  alert('name match');
} else {
  alert('no match');
}

indexOf returns -1 if there was no match in the array, otherwise it returns the index of the match.

You could also use array.includes in a similar fashion.

Matt Holland
  • 2,190
  • 3
  • 22
  • 26