简体   繁体   中英

Checking input against array - Javascript

I'm totally new, so excuse any faux pas. I searched for a solution, but couldn't find anything that answered my question, or at least anything that I could understand.

So here goes: I'd like to iterate through each object in this array and check if firstName ("Akira", in this case) matches up to any of the firstNames within my "contacts" array. At this stage, I'd just like to return the index number of the object(if this is possible). If not, please let me know how I can do this, in the most elementary, 5-year old way possible. Thank you!

var contacts = [
{
    "firstName": "Akira",
    "lastName": "Laine",
    "number": "0543236543",
    "likes": ["Pizza", "Coding", "Brownie Points"]
},
{
    "firstName": "Harry",
    "lastName": "Potter",
    "number": "0994372684",
    "likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
    "firstName": "Sherlock",
    "lastName": "Holmes",
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
},
{
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["Javascript", "Gaming", "Foxes"]
}

function lookUpProfile(firstName, prop){
  for (var i = 0; i < contacts.length; i++) {
   if (contacts[i][firstName] == firstName){
      return i; 
   } 
  }   
}

lookUpProfile("Akira", "likes");

your code has an error you have no closing "]" for your contacts variable, also when accessing object properties use code contacts[i]["firstname"]

 var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number": "0543236543", "likes": ["Pizza", "Coding", "Brownie Points"] }, { "firstName": "Harry", "lastName": "Potter", "number": "0994372684", "likes": ["Hogwarts", "Magic", "Hagrid"] }, { "firstName": "Sherlock", "lastName": "Holmes", "number": "0487345643", "likes": ["Intriguing Cases", "Violin"] }, { "firstName": "Kristian", "lastName": "Vos", "number": "unknown", "likes": ["Javascript", "Gaming", "Foxes"] }]; function lookUpProfile(firstName, prop){ var ret = -1; for (var i = 0; i < contacts.length; i++) { if (contacts[i]["firstName"] == firstName){ ret = i; } } console.log(ret); } lookUpProfile("Akira", "likes"); 

you can refer this answer. following are the best way to access JSON objects.

 function lookUpProfile(firstName, prop){
      for (var i = 0; i < contacts.length; i++) {
       if (contacts[i]["firstName"] == firstName){
          return i; 
       } 
      }   
    }

or

function lookUpProfile(firstName, prop){
  for (var i = 0; i < contacts.length; i++) {
   if (contacts[i].firstName == firstName){
      return i; 
   } 
  }   
}

Object properties can be accessed by dot notation, or your have to quotes your key as it is a string.

 if (contacts[i].firstName == firstName){
  return i; 
 } 

check fiddle

You forgot to close up contacts array and called property wrong inside the function

 var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number": "0543236543", "likes": ["Pizza", "Coding", "Brownie Points"] }, { "firstName": "Harry", "lastName": "Potter", "number": "0994372684", "likes": ["Hogwarts", "Magic", "Hagrid"] }, { "firstName": "Sherlock", "lastName": "Holmes", "number": "0487345643", "likes": ["Intriguing Cases", "Violin"] }, { "firstName": "Kristian", "lastName": "Vos", "number": "unknown", "likes": ["Javascript", "Gaming", "Foxes"] } ]; function lookUpProfile(firstName, prop){ for (var i = 0; i < contacts.length; i++) { if (contacts[i].firstName === firstName){ console.log(i); return i; } } } lookUpProfile("Sherlock", "likes"); 

Your code is confusing the variable firstName to the key firstName.

In your lookUpProfile function, change this line :

if(contacts[i].firstName == firstName)

Explanation

Just change your function like -

function lookUpProfile(firstName, prop){
 for (var i = 0; i < contacts.length; i++) {
  if (contacts[i].firstName === firstName){
  return i; 
   } 
  }   
}

And Dont use '==' Use '===' in javaScript

Your code has some minor errors, but except those, everything looks fine to me. The first error is that you haven't closed the contacts array. You have opened the array here: var contacts = [ and started listing the contacts, but after that, you have to close this array with this character ] .

And the second issue is something that you are really care about. When you are checking the firstName you are passing the same parameter that you give to the function, that being said, you are not checking if contacts[i].firstName === "Akira" but contacts[i].Akira === "Akira" . And none of the objects has Akira property.

You can try contacts[i].firstName or contacts[i].["firstName"] . Both will solve your problem.

You can find more explanation here: http://www.w3schools.com/js/js_properties.asp

Looking at the arguments you want to accept in the function, I assume that you want the property of the given contact.

You can access a property of an object using dot notation like contacts[0].firstName .

You can also access it using array with associated key like contacts[0]["firstName"] .

 var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number": "0543236543", "likes": ["Pizza", "Coding", "Brownie Points"] }, { "firstName": "Harry", "lastName": "Potter", "number": "0994372684", "likes": ["Hogwarts", "Magic", "Hagrid"] }, { "firstName": "Sherlock", "lastName": "Holmes", "number": "0487345643", "likes": ["Intriguing Cases", "Violin"] }, { "firstName": "Kristian", "lastName": "Vos", "number": "unknown", "likes": ["Javascript", "Gaming", "Foxes"] } ]; function lookUpProfile(firstName, prop){ for (var i = 0; i < contacts.length; i++) { if (contacts[i].firstName == firstName){ console.log(i); return contacts[i][prop]; } } } console.log(lookUpProfile("Akira", "likes")); 

Ok so starting with your search function:

// Prop parameter wasn't used so I removed it.
function lookUpProfile(firstName){
  for (var i = 0; i < contacts.length; i++) {
   // If you are using an array accessor for the properties you want to throw
   // quotes around it.  You could also access it like so contacts[i].firstName.
   // What you had previously was using the value of "firstName" to try to
   // access the "firstName" property.  What your code actually tried was to
   // access the "Akira" property which doesn't exist.  
   // 
   // Also until you get stronger in javascript it is safer to use the "===" 
   // strict equality as this checks for type and value equality.  (ex 0 === "0" will be false)
   if (contacts[i]['firstName'] === firstName){
      // By returning here you are saying that no other object can have the
      // same "firstName" value.  If that isn't true you will want to store
      // the index in a variable outside of this loop and return it later.
      //
      // Another option here is to just return "contacts[i]" that way you
      // have a reference to the object you are searching for.
      return i; 
   } 
  }   
}

In general when starting out I would suggest using strict equality ("==="/"!==") as it will behave more intuitively and fail sooner. If you use "=="/"!=" javascript will try to convert types for you if they don't match which can lead to unintended behavior.

If you write this code then you will get the output like this [0, undefined, undefined, undefined]. Where 0 is your matched character index.

var lookUpProfile = function(matchString) { var returnVal = function(item,index) { if(item.firstName == matchString) return index; }; return returnVal; }; var profileIndexHolder = contacts.map(lookUpProfile('Sherlock')) console.log(profileIndexHolder);

var lookUpProfile = function(matchString) { var returnVal = function(item,index) { if(item.firstName == matchString) return index; }; return returnVal; }; var profileIndexHolder = contacts.map(lookUpProfile('Sherlock')) console.log(profileIndexHolder);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM