简体   繁体   English

通过对象属性识别对象数组

[英]Identify an array of objects by object property

My question: 我的问题:

I have an array of objects as such 我有这样的对象数组

var people = [
        {name: 'Dan'  ,  age: '20', favoriteColor : 'blue'}, 
        {name: 'Bob'  ,  age: '35', favoriteColor : 'red' }, 
        {name: 'Frank',  age: '22', favoriteColor : 'green'}, 
        {name: 'Ed'   ,  age: '27', favoriteColor : 'yellow'}
]

I need to be able to identify the objects in the array by their name property. 我需要能够通过它们的name属性来识别数组中的对象。 [It's important to note that the name property for each object in the array WILL be unique]. [需要注意的是,数组中每个对象的name属性将是唯一的]。 However, they are not ordered by any particular pattern. 但是,它们没有按任何特定模式排序。 So people[0] may or may not equal the object with a 'name' of 'Dan'. 因此,people [0]可能等于或可能不等于“名称”为“ Dan”的对象。

I want to be able to access the data by organizing it so that 我希望能够通过组织数据来访问数据,以便

people.Dan 

returns the object 返回对象

{age: '20', favoriteColor: 'blue'}

I feel like this should be relatively simple, but I don't really know the words to describe the issue to be able to find the proper solution. 我觉得这应该相对简单一些,但是我真的不知道用什么词来形容这个问题,以便能够找到合适的解决方案。

EDIT: For anyone reading this in the future, I decided to go with Elliot's solution instead of using underscore.js. 编辑:对于以后阅读此书的任何人,我决定采用Elliot的解决方案,而不是使用underscore.js。 They both solve the problem, but it ended up being easier just to implement another function. 他们都解决了这个问题,但是最终仅仅实现另一个功能变得更加容易。

Right now people is an array. 现在, people是一个数组。 You need to restructure it into an object, where each name is a property returning the rest of that object. 您需要将其重组为一个对象,其中每个名称都是返回该对象其余部分的属性。 Here's one way to do that: 这是一种方法:

var tempPeople = {};
for(var i = 0, len = people.length; i<len; i++) {
    tempPeople[people[i].name] = people[i];
}

people = tempPeople;

You could also leave people as an array and instead use Array.filter to select by name: 您也可以将people保留为数组,而使用Array.filter按名称选择:

var dan = people.filter(function(person) { return person.name == "Dan" })[0]; // returns the first person named Dan

You should use underscore.js or lodash . 您应该使用underscore.jslodash They have a method called findWhere which does exactly what you need. 他们有一个名为findWhere的方法,它可以完全满足您的需求。 The method _.where will return an array if there is more than one matching object. 如果有多个匹配对象,则_.where方法将返回一个数组。

_.findWhere(people, {name: "dan"});
// will return
// {name: 'Dan', age: '20', favoriteColor: 'blue'}

Make an object constructor. 创建一个对象构造函数。 Write a custom method. 编写自定义方法。

function person(name,age,favoriteColor) {
    this.name = name;
    this.age = age;
    this.favoriteColor = favoriteColor;
    this.getInfo = function() {
        return this.age + " - " + this.favoriteColor;
    }
}

var people = [];

people.push(new person('dan','20','blue'));

alert(people[0].getInfo());

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

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