简体   繁体   English

如果在JavaScript中找到对象数组,则返回对象的属性

[英]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(firstName, prop) ,它对于输入数据:

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. 使用.find()函数( ES6 )查找项目,并使用方括号[]语法返回相应的属性。

 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. 你的问题是你试图用带有数字indeces的for循环遍历对象。 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. 而且,contacts [i]是一个对象,因此没有length属性,所以你要比较0 < undefined ,它总是假的。

This results in your conditional check for property never occurring. 这导致您对属性的条件检查永远不会发生。 In addition to this, prop is an accessor here. 除此之外,prop是这里的访问者。 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. 为了正确返回属性值,您需要在当前对象上以[prop]的形式将其用作访问器。

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 DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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