我有一个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
然后使用URL的split
输出json对象,这样我就可以得到URL的第二部分,即cat1, cat2, cat3
。每个网址没有确定的长度。
您知道如何实现以下输出吗?我正设法在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
任何帮助将不胜感激。谢谢。
答案 0 :(得分:3)
您可以获得第一个路径的链接并对数组进行排序。
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);
答案 1 :(得分:1)
使用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中的示例: