javascript 搜索 JS 对象的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7569718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search JS Object for Value
提问by doremi
Say I have an object:
说我有一个对象:
userInfo
And I want to search each node of userInfo to see if the key 'username' has a value equal to foo.
我想搜索 userInfo 的每个节点,看看键 'username' 的值是否等于 foo。
userInfo[x].username == "foo"
Is there a better way of doing the following?
有没有更好的方法来执行以下操作?
var matchFound = false;
for (var i = 0, len = userInfo.length; i < len; i++)
matchFound = userInfo[i].username == "foo";
采纳答案by Peter Rebholz
There isn't really a better (more efficient) way without introducing another data structure. The answer really depends on your usage but you could do a few different things:
如果不引入另一种数据结构,真的没有更好(更有效)的方法。答案实际上取决于您的使用情况,但您可以做一些不同的事情:
Create separate 'indexes' using hashes. These structures would map keys to the items or the index in the source array. JavaScript objects/hashes support key based lookup and should be efficient.
userinfo[x].username = "foo"; // Index the objects usersByName = {}; usersByName["foo"] = userinfo[x]; // -- OR -- index the array indices var usersByName["foo"] = x; // Test for key "foo" in usersByName; // true
You'll have to put in a little more work to maintain consistency between the index and the source array. It's probably best to wrap both in another object to manage the contents of both. This approach is nice if there are multiple fields that you want to look objects up by.
If you don't care about the order of the collection you could just change the whole thing to a hash and index by username
var userinfo = {}; userinfo["foo"] = {username: "foo", firstName: "Foo", lastName: "Bar"};
使用哈希创建单独的“索引”。这些结构将键映射到源数组中的项目或索引。JavaScript 对象/哈希支持基于键的查找并且应该是高效的。
userinfo[x].username = "foo"; // Index the objects usersByName = {}; usersByName["foo"] = userinfo[x]; // -- OR -- index the array indices var usersByName["foo"] = x; // Test for key "foo" in usersByName; // true
您将不得不做更多的工作来保持索引和源数组之间的一致性。最好将两者都包装在另一个对象中以管理两者的内容。如果您想根据多个字段查找对象,则此方法非常有用。
如果您不关心集合的顺序,您可以将整个内容更改为按用户名的哈希和索引
var userinfo = {}; userinfo["foo"] = {username: "foo", firstName: "Foo", lastName: "Bar"};
One thing to think about, though, is if the efficiency gains are going to outweigh the increased code complexity of maintaining indexes. If you aren't doing a lot of searches and you don't have tons of items in the userinfo collection it may make more sense to just write a general use searching function or use a library like what Philip Schweiger was mentioning.
不过,需要考虑的一件事是,效率的提升是否会超过维护索引所增加的代码复杂性。如果您没有进行大量搜索并且在 userinfo 集合中没有大量项目,那么编写一个通用搜索功能或使用 Philip Schweiger 提到的库可能更有意义。
function findObjectByAttribute (items, attribute, value) {
for (var i = 0; i < items.length; i++) {
if (items[i][attribute] === value) {
return items[i];
}
}
return null;
}
var userinfo = [];
userinfo[0] = {username: "foo"};
console.log(findObjectByAttribute(userinfo, "username", "foo"));
回答by Kevin Bowersox
No need for the ternary operator, consider the following:
不需要三元运算符,请考虑以下事项:
var matchFound = false;
for (var i = 0, len = userInfo.length; i < len; i++)
{
matchFound = userInfo[i].username == "foo";
if(matchFound){
break;
}
}
回答by Philip Schweiger
The underscore JS library has some handy methods to work with data collections - for instance, the select method
下划线 JS 库有一些方便的方法来处理数据集合——例如,select 方法
Implementing it would like like this:
实现它会像这样:
var userInfo = {
'x':{
username: "foo",
password:'dlji'
},
'y':{
username: "bar" ,
password:'adfasf'
},
'z': {
username: 'foo',
password:'d3alj4i'
}
};
var found = _.select(userInfo, function(node){
return node.username === "foo"
});
console.dir (found);
Underscore isn't very large, and while you can do this in native JS too, I think it does a good job implementing the solutions you'd come up with on your own. Basically, it gives you a lot of the JS features you'd think should be there anyway.
下划线不是很大,虽然您也可以在本机 JS 中执行此操作,但我认为它可以很好地实现您自己提出的解决方案。基本上,它为您提供了许多您认为无论如何都应该具备的 JS 功能。