我有一个javascript对象数组,每个对象有三个字段,如下所示:
var people = [
{first: "john", middle: "james", last: "doe"},
{first: "jane", middle: "kate", last: "smith"},
...
{first: "kathy", middle: "rose", last: "green"},
];
我希望能够根据任何字段查询此数组,并获取匹配的对象。例如,我希望能够调用类似people.getByMiddle("kate")
的内容并返回{first: "jane", middle: "kate", last: "smith"}
是否有一种数据结构能够以这种方式更容易地关联这些内容,或者我应该只编写三个独立的函数,每个函数都迭代我的数据并搜索匹配项?我不希望任何依赖于数组排序的东西。
答案 0 :(得分:1)
function getByProperty (arr, prop, value) {
arr.forEach(function (item) {
if (item[prop] === value) {
return item;
}
});
}
你可以这样使用它:
var result = getByProperty(people, 'middle', 'kate');
答案 1 :(得分:1)
这是一个可能的解决方案:
function findPeople(anArray, objProperty, searchPattern) {
return anArray.filter(function(person){
return searchPattern.test(person[objProperty]);
})
}
答案 2 :(得分:0)
我只能想到这个:
var people = [
{first: "john", middle: "james", last: "doe"},
{first: "jane", middle: "kate", last: "smith"},
{first: "kathy", middle: "rose", last: "green"},
];
people.getByMiddle = function(name){
var newSelection = [];
for(i in this){
var item = this[i];
if(item.middle == name)
newSelection.push(item);
}
return newSelection;
};
people.getByMiddle("kate");