我在过去的两个月里一直在尝试编写脚本!很多学习!由于我在这方面完全是新手,我很想知道你是否可以帮助我!
看,我刚刚完成了一个JSON(一个大的),这与我在这里的内容很接近
[{
"League": "English Championship",
"Champion": "Team 4",
"Vice": "Team 3",
"Third": "Team 1",
}, {
"League": "European Championship",
"Champion": "Team 3",
"Vice": "Team 2",
"Third": "Team 1
}]
我想计算一个特定团队在元素'冠军','副'和'第三'中出现的次数,所以我可以创建这样的东西:
______|_1st_|_2nd_|_3rd_
Team 1|__0__|__0__|__2__|
Team 2|__0__|__1__|__0__|
Team 3|__1__|__1__|__0__|
Team 4|__1__|__0__|__0__|
当我正在研究JS和jQuery时,我想知道是否可以为这个表开发一个新的数组。如果它真的很难,我可以使用excel来表示所有内容,然后再次进入JSON。
我只想要一个开头小费!
谢谢
答案 0 :(得分:1)
您可以使用Array.prototype.reduce()
,for..in
循环。请注意,"
"Third": "Team 1
var data = [{
"League": "English Championship",
"Champion": "Team 4",
"Vice": "Team 3",
"Third": "Team 1",
}, {
"League": "European Championship",
"Champion": "Team 3",
"Vice": "Team 2",
"Third": "Team 1"
}];
var res = data.reduce(function(obj, b, index) {
if (!index) { // if `index` is equal to `0`
for (var prop in b) { // iterate properties of `b` object in `data` array
if (prop !== "League") { // exclude `"League"` from next block
// set `obj` : `{}` set at third parameter to `.reduce()`
// property to `b[prop]`, value to `1`
obj[prop] = {[b[prop]]:1};
}
}
} else {
for (var prop in obj) { // iterate properties of `obj` object
if (obj[prop][b[prop]]) { // if `obj[prop][b[prop]]` property is defined
++obj[prop][b[prop]]; // increment value
}
}
};
return obj // return `obj`
}, {});
console.log(res);
答案 1 :(得分:1)
data = [{
"League": "English Championship",
"Champion": "Team 4",
"Vice": "Team 3",
"Third": "Team 1",
}, {
"League": "European Championship",
"Champion": "Team 3",
"Vice": "Team 2",
"Third": "Team 1"
}]
function getCount(position, team) {
return data.filter(function(x) {
return x[position] == team
}).length
}
console.log(getCount('Champion', 'Team 1'))
console.log(getCount('Vice', 'Team 1'))
console.log(getCount('Third', 'Team 1'))
console.log(getCount('Champion', 'Team 2'))
console.log(getCount('Vice', 'Team 2'))
console.log(getCount('Third', 'Team 2'))
console.log(getCount('Champion', 'Team 3'))
console.log(getCount('Vice', 'Team 3'))
console.log(getCount('Third', 'Team 3'))
答案 2 :(得分:0)
您可以使用Array.prototype.reduce()获取您想要的数据结构
const json = [{
"League": "English Championship",
"Champion": "Team 4",
"Vice": "Team 3",
"Third": "Team 1"
}, {
"League": "European Championship",
"Champion": "Team 3",
"Vice": "Team 2",
"Third": "Team 1"
}];
const sum = json.reduce(function (next, res) {
const initObj = () => ({
"Champion": 0,
"Vice": 0,
"Third": 0
});
if(!next[res["Champion"]]) {
next[res["Champion"]] = initObj();
}
if (!next[res["Vice"]]) {
next[res["Vice"]] = initObj();
}
if (!next[res["Third"]]) {
next[res["Third"]] = initObj();
}
next[res["Champion"]]["Champion"] += 1;
next[res["Vice"]]["Vice"] += 1;
next[res["Third"]]["Third"] += 1;
return next;
}, {});
console.log(sum);