简体   繁体   中英

Return object's property if it is found into an array of objects in JavaScript

I have the following array of objects:

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"]
    }
];

I want to define a function, lookUpProfile(firstName, prop) , which for the input data:

lookUpProfile("Akira", "likes");

will return:

["Pizza", "Coding", "Brownie Points"]

This is my solution so far which doesn't return something till now:

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

Has anyone any idea to solve this? Thanks

You can try to do like this. Find the item with .find() function ( ES6 ) and return the appropriate property using bracket [] syntax.

 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 lookUpProfileES6(name, prop){ var found = contacts.find(item => item.firstName === name); if(found){ return found[prop]; } } function lookUpProfileES5(name, prop){ var found = null; for(var i = 0; i < contacts.length; i++){ if(contacts[i].firstName === name){ found = contacts[i]; break; } } if(found){ return found[prop]; } } var resultES6 = lookUpProfileES6("Akira", "likes"); var resultES5 = lookUpProfileES5("Akira", "likes"); console.log(resultES6); console.log(resultES5); 

You problem is that you are trying to loop over object with for loop with numeric indeces. You don't need second loop at all. It could be as simple as

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

 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) { if (contacts[i].hasOwnProperty(prop)) return contacts[i][prop]; } } } console.log(lookUpProfile("Akira", "likes")) 

The problem with your code was this line:

for(var j = 0; j < contacts[i].length; j++){

There is no need to attempt to iterate again here. Moreover, contacts[i] is an object and thus has no length property, so you are comparing 0 < undefined which is always false.

This results in your conditional check for property never occurring. In addition to this, prop is an accessor here. So while it may hold the property name it does not hold the property value. In order to properly return the property value, you need to use it as an accessor in the form of [prop] on the current object.

Remove the second iteration, properly access the contact object, and your function will work properly.

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

You can do like this

// Create a function which will filter out the requirement
var filtered = function(name, likes) {
  var _toRet = ''
  contacts.filter(function(elem, index) {
    // check if the first name is same as requires
    // check if the object have property likes
    // Since the requirement is to search the likes array
    if (elem.firstName === name && elem.hasOwnProperty(likes)) {
      _toRet = elem[likes]  
    }
    return _toRet  // return from filter callback

  })
return _toRet  // return from the function
}

console.log(filtered('Akira', 'likes'))

DEMO

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