我如何在没有JavaScript中的密钥的情况下对foreach结果进行分组



我有一个在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输出JSON对象,然后split URL,以便我可以获取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/news或https://example.com/events

任何帮助将不胜感激。谢谢。

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

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);

使用unterscore.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/

最新更新