+ 1
Help with retrieving array value from object array
Hi can someone maybe guide me here please? 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'); } }
4 Respuestas
+ 2
What I did was create a boolean variable so we can track if we have a match. Then we use a loop so we can iterate through the array and check each name/value set against the name the user inputted. If we find a match, we'll set match to true, otherwise it'll remain as false. After we're done looping, alert user if we found a match or not.
If you look at the array's structure in your code, basically each { } is an element in the array, and then you have the name/values that are basically elements of that element.
arrayFullNames[i]["name"]
^the [i] is iterating through the main elements of the array, and then the ["name"] is accessing the named element. We use that to check if the named element contains a value equal to that of what the user inputted.
https://code.sololearn.com/WB1dE4zIX3mE/#js
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", '');
var match = false;
for(var i = 0; i < arrayFullNames.length; ++i){
if(arrayFullNames[i]["name"] == userQuestion){
match = true;
}
}
if(match) {
alert("Name match!");
} else {
alert("Name mismatch!");
}
}
onRegister();
+ 1
Thank you so much for your explanation, it was very detailed and I understand better now.