有没有更有效的方法来查找返回对象的子集?
这可行,但看起来非常笨拙。有问题的方法是streetInObj,obj是一个对象,可以具有对应于streets.all的键“p”、“f”、“t”、“r”。所以我只是想返回对象中存在的所有街道。
define(['underscore'], function (_) {
var streets = {
all: [
{abbrev: "p", name: "Preflop"},
{abbrev: "f", name: "Flop"},
{abbrev: "t", name: "Turn"},
{abbrev: "r", name: "River"}
],
streetsInObj: function(obj) {
self.obj = obj;
streets = [];
_.map(self.all, function(street, obj) {
if(self.obj[street.abbrev]) {
streets.push(street);
}
});
return streets;
}
};
var self = streets;
return self;
});
This works but seems incredibly clumsy. The method in question is streetsInObj, and obj is an object that can have the keys "p", "f", "t", "r" which correspond to streets.all. So I'm just trying to return all of the streets that exist in the object.
define(['underscore'], function (_) {
var streets = {
all: [
{abbrev: "p", name: "Preflop"},
{abbrev: "f", name: "Flop"},
{abbrev: "t", name: "Turn"},
{abbrev: "r", name: "River"}
],
streetsInObj: function(obj) {
self.obj = obj;
streets = [];
_.map(self.all, function(street, obj) {
if(self.obj[street.abbrev]) {
streets.push(street);
}
});
return streets;
}
};
var self = streets;
return self;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
只有 4 条街道应该没问题。如果您有 4000 条街道,而该对象的街道数量可能要少得多,那么您可能可以通过从街道对象开始获得一些速度,例如:
然后执行:
What about:
That should be fine with only 4 streets. If you had 4000 streets, and the object was likely to have far fewer, you could probably gain some speed by starting with an object of streets, like:
and then doing:
在这里,您将返回数组的子集(全部)。只是想指出,如果您想返回 javascript 对象的子集属性,您可以使用 _.pick 功能。
Here you are returning a subset of an array (all). Just wanted to make note that in case you wanted to return a subset properties of a javascript object you can use _.pick function.