如何在匹配其属性之一后打印对象的属性

时间:2016-06-05 16:13:58

标签: javascript

我想匹配对象的属性值之一,如果它匹配该属性,我需要打印该对象的所有其他属性。  我正在尝试匹配firstName属性并打印其剩余的。

这是代码

      var friends=new Object();
  friends.steve={
  firstName:"Steve",
  lastName:"smith",
  number:"8861785484",
  address:['rajajinagar','bangalore','560010']
  };

friends.bill={
firstName:"Bill",
lastName:"gates",
number:"9845378136",
address:['shivajinagar','bangalore','560018']
};


var search=function(name){
    for(firstName in friends){
        if(friends[name].firtstName===name){
            console.log(friends[name]);
            return (friends[name]);

            }


        }

    }
 search("steve");

输出应该是“steve”对象的所有属性,如firstName,lastName,number和address

3 个答案:

答案 0 :(得分:0)

交朋友一个对象数组,而不是对象的对象,然后尝试这个:

for(var i = 0;i<friends.length;i++){
    if(friends[i].firstName===name){
        console.log(friends[i]);
        return friends[i];
    }
}

答案 1 :(得分:0)

您可以在属性上使用Array#forEach进行迭代(使用Object.keys)并检查.dropdown .dropdown-content { visibility: hidden; position: absolute; background-color: #ed393c; -webkit-transition: visibility 500ms, opacity 500ms; -moz-transition: visibility 500ms, opacity 500ms; -ms-transition: visibility 500ms, opacity 500ms; -o-transition: visibility 500ms, opacity 500ms; transition: visibility 500ms, opacity 500ms; } 是否等于firstName。这个提议寻找所有的史蒂夫。

变量name表示对象的属性名称,例如k'steve'

'bill'

带有for ... in循环的提案。

var friends = { steve: { firstName: "Steve", lastName: "smith", number: "8861785484", address: ['rajajinagar', 'bangalore', '560010'] }, bill: { firstName: "Bill", lastName: "gates", number: "9845378136", address: ['shivajinagar', 'bangalore', '560018'] } },
    search = function (name) {
        Object.keys(friends).forEach(function (k) {
            if (friends[k].firstName.toLowerCase() === name.toLowerCase()) {
                console.log(friends[k]);
            }
        });
    };

search("steve");

答案 2 :(得分:0)

我会喜欢这个;

var friends = new Object(),
  getDetail = n => friends[n.toLowerCase()];
friends.steve={
  firstName:"Steve",
  lastName:"smith",
  number:"8861785484",
  address:['rajajinagar','bangalore','560010']
  };

friends.bill={
  firstName:"Bill",
  lastName:"gates",
  number:"9845378136",
  address:['shivajinagar','bangalore','560018']
};
console.log(getDetail("Steve"));

可能会这样;