【问题标题】:How do I group forEach results without a key in javascript?如何在没有 javascript 键的情况下对 forEach 结果进行分组?
【发布时间】:2019-07-01 13:29:41
【问题描述】:

我有一个 WordPress 中的 url 列表,需要通过循环以有效的方式进行排序。

var urlList = [
  {
    "URL": "https://example.com/cat1/aa/bb/cc",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat2/aa",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat1/aa/bb/cc/dd/ee",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat3/aa/bb/cc/",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat2/aa/bb",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat1/aa/bb",
    "Last crawled": "Jun 23, 2019"
  }
]

urlList.forEach(function(item) {
    var myUrl = item.URL.split("/");
    console.log("https://example.com/" + myUrl[3]);
});

我尝试输出带有forEach 然后split url 的json 对象,这样我就可以获得url 的第二部分,即cat1, cat2, cat3。每个 url 没有明确的长度。

你知道我怎样才能实现下面的输出吗?我的目标是在 forEach 循环内完成。

https://example.com/cat1
https://example.com/cat1
https://example.com/cat1
https://example.com/cat2
https://example.com/cat2
https://example.com/cat3

注意:类别不限于cat1,cat2,cat3。也可以是https://example.com/newshttps://example.com/events

非常感谢任何帮助。谢谢。

【问题讨论】:

  • 那么,为什么不直接.sort()

标签: javascript jquery html css wordpress


【解决方案1】:

您可以获得第一个路径的链接并对数组进行排序。

var urlList = [{ URL: "https://example.com/cat1/aa/bb/cc", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat2/aa", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat1/aa/bb/cc/dd/ee", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat3/aa/bb/cc/", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat2/aa/bb", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat1/aa/bb", "Last crawled": "Jun 23, 2019" }],
    result = urlList
        .map(({ URL }) => URL.match(/^https:\/\/example.com\/[^\/]+(?=\/)/)[0])
        .sort((a, b) => a.localeCompare(b));

console.log(result);

【讨论】:

  • 您不需要将比较器传递给.sort - 默认情况下应该以相同的方式对其进行排序。不过,以防万一需要定制,这也不是一个坏主意。
  • 嗨。谢谢你。有没有其他方法可以做到这一点而不将其限制为cat 类别?
  • 你有固定的前缀,并且想要在前缀后面的第一个路径上只设置一个路径吗?
  • https://example.com 是我能看到的唯一固定部分。这次真是万分感谢。像魅力一样工作
【解决方案2】:

一个使用 underscore.js 的例子(你可以用我拆分的下划线链接调用):

var s = _.map(urlList, function(i) {
  return i.URL.split("/")[3];
});
var sorted = _.sortBy(s)
var projection = _.map(sorted, function(p) {
  console.log("https://example.com/" + p);
});

jsfiddle 中的示例:

https://jsfiddle.net/1nwg9pq7/

【讨论】:

  • 嗨。谢谢你。如果可能的话,我尽量不使用库
猜你喜欢
  • 1970-01-01
  • 2013-10-16
  • 2019-11-08
  • 2022-01-25
  • 2011-12-04
  • 2020-09-24
  • 2011-03-13
  • 2020-12-29
  • 2017-10-31
相关资源
最近更新 更多