3 回答
TA贡献2003条经验 获得超2个赞
您可以reduce在数组对象上使用该方法。
let data = [{
url:"https://example1.com/a",
something:"ABC"
},{
url:"https://example1.com/b",
something:"DEF"
},{
url:"https://example2.com/c",
something:"GHI"
},{
url:"https://example2.com/d",
something:"JKL"
}];
let ret = data.reduce((acc, cur) => {
let host = cur['url'].substring(8, 20); // hardcoded please use your own
if (acc[host])
acc[host].push(cur);
else
acc[host] = [cur];
return acc;
}, {})
console.log(ret);
TA贡献1826条经验 获得超6个赞
const dataFromQuestion = [{
url:"https://example1.com/a",
something:"ABC"
},{
url:"https://example1.com/b",
something:"DEF"
},{
url:"https://example2.com/c",
something:"GHI"
},{
url:"https://example2.com/d",
something:"JKL"
}];
function listOfDictionaryToDictionaryOfList(input, keyMapper) {
const result = {};
for (const entry of input) {
const key = keyMapper(entry);
if (!Object.prototype.hasOwnProperty.call(result, key)) {
result[key] = [];
}
result[key].push(entry);
}
return result;
}
function getHost(data) {
const url = new URL(data.url);
return url.host;
}
console.log(listOfDictionaryToDictionaryOfList(dataFromQuestion, getHost));
TA贡献1796条经验 获得超4个赞
data.reduce((groups, item) => {
let host = new URL(item.url).hostname;
(groups[host] || (groups[host] = [])).push(item);
return groups;
}, {});
单行(虽然很神秘)
data.reduce((g, i, _1, _2, h = new URL(i.url).hostname) => ((g[h] || (g[h] =[])).push(i), g), {});
添加回答
举报