有没有更有效的方法来查找返回对象的子集?

发布于 2024-12-29 12:48:59 字数 632 浏览 2 评论 0原文

这可行,但看起来非常笨拙。有问题的方法是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

在巴黎塔顶看东京樱花 2025-01-05 12:48:59

怎么样:

return _.filter(self.all, function(s) { 
    return s.abbrev in obj;
});

只有 4 条街道应该没问题。如果您有 4000 条街道,而该对象的街道数量可能要少得多,那么您可能可以通过从街道对象开始获得一些速度,例如:

all: {
  p: {abbrev: "p", name: "Preflop"},
  f: {abbrev: "f", name: "Flop"},
  t: {abbrev: "t", name: "Turn"},
  r: {abbrev: "r", name: "River"}
}

然后执行:

return _.map(_.keys(obj), function(k) { 
    return self.all[k]; 
});

What about:

return _.filter(self.all, function(s) { 
    return s.abbrev in obj;
});

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:

all: {
  p: {abbrev: "p", name: "Preflop"},
  f: {abbrev: "f", name: "Flop"},
  t: {abbrev: "t", name: "Turn"},
  r: {abbrev: "r", name: "River"}
}

and then doing:

return _.map(_.keys(obj), function(k) { 
    return self.all[k]; 
});
自控 2025-01-05 12:48:59

在这里,您将返回数组的子集(全部)。只是想指出,如果您想返回 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文