我试图汇总标题名称和来自不同标题来源的数量。我成功地从对象数组中删除了重复项,并且仅从每个源中仅显示原始版本的标题,而没有任何重复项。但是我没有详细说明每个标题名称在 json 中有多少个重复项。就像在这里,我们每个人都有 4 个。但我无法获得全部重复项。这部分是我在代码中添加的else
条件。ifExistFlag
我还添加了一个小提琴链接
var inputJson = [{
"Sources": [{
"title": "Title Name",
"source": "SourceName1",
"date": "07-05-2013 00:38:40",
"link": "Link to 1"
}, {
"title": "Title Name",
"date": "07-05-2013 00:24:17",
"source": "SourceName2",
"link": "Link to 2"
}
]
}, {
"Sources": [{
"title": "Title Name",
"source": "SourceName1",
"date": "07-05-2013 00:38:40",
"link": "Link to 1"
}, {
"title": "Title Name",
"date": "07-05-2013 00:24:17",
"source": "SourceName2",
"link": "Link to 2"
}
]
}, {
"Sources": [{
"title": "Title Name",
"source": "SourceName1",
"date": "07-05-2013 00:38:40",
"link": "Link to 1"
}, {
"title": "Title Name",
"date": "07-05-2013 00:24:17",
"source": "SourceName2",
"link": "Link to 2"
}
]
}, {
"Sources": [{
"title": "Title Name",
"source": "SourceName1",
"date": "07-05-2013 00:38:40",
"link": "Link to 1"
}, {
"title": "Title Name",
"date": "07-05-2013 00:24:17",
"source": "SourceName2",
"link": "Link to 2"
}
]
}
]
$(document).ready(function () {
var sourceList = AggregateSource(inputJson);
var sourcePrint = printFinalSourceData(sourceList);
$("#output").html(sourcePrint);
});
function AggregateSource(sourceArray, number) {
var l = {};
var finalArray = [];
for (var i = 0; i < sourceArray.length; i++) {
for (var j = 0; j < sourceArray[i].Sources.length; j++) {
if (l.hasOwnProperty(sourceArray[i].Sources[j].source) == false) {
l[sourceArray[i].Sources[j].source] = [];
var m = {};
m["title"] = sourceArray[i].Sources[j].title;
m["link"] = sourceArray[i].Sources[j].link;
m["date"] = sourceArray[i].Sources[j].timeStamp;
m["count"] = 1;
l[sourceArray[i].Sources[j].source].push(m);
} else {
var ifExistFlag = true;
for (var k = 0; k < l[sourceArray[i].Sources[j].source].length; k++) {
if (l[sourceArray[i].Sources[j].source][k]["title"] == sourceArray[i].Sources[j].title) {
ifExistFlag = false;
}
}
if (ifExistFlag == true) {
m["title"] = sourceArray[i].Sources[j].title;
m["date"] = sourceArray[i].Sources[j].timeStamp;
m["link"] = sourceArray[i].Sources[j].link;
l[sourceArray[i].Sources[j].source].push(m);
} else {
// alert(l[sourceArray[i].Sources[j].source][j]["count"])
}
}
}
}
finalArray.push(l);
return finalArray;
}
function printFinalSourceData(inputArray) {
var sourceHTML = '';
for (var k = 0; k < inputArray.length; k++) {
for (key in inputArray[k]) {
for (var i = 0; i < inputArray[k][key].length; i++) {
sourceHTML += "<span style='width:80%; float:left; font-size:14px;'><a href='" + inputArray[k][key][i].link + "' target='_blank' style='text-decoration:none; color:#333333; font-weight:bold;'>" + inputArray[k][key][i].title + "</a></span><br><span style='width:80%;float:left; font-size:10px; color: #3f4041;'>" + key.split("_").join(" "); + "</span><br>";
}
}
}
return sourceHTML;
}