Retrieving array value from object array
This question already has an answer here:
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()
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.
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;
}
链接地址: http://www.djcxy.com/p/24544.html
上一篇: 我怎样才能返回2个值与getElementsByClassName()?
下一篇: 从对象数组中检索数组值