我有这个数组数据
var array = [
{"package": "20Dresses - Shop Women Fashion", "total": 4857},
{"total": 24, "competingapps": "com.stylecracker.android"},
{"total": 578, "competingapps": "com.shopping.limeroad"},
{"total": 291, "competingapps": "com.craftsvilla.app"},
{"total": 430, "competingapps": "com.voonik.android"}
];
从这个数组数据中,我必须为维恩图制作以下数据结构。
var vennSets = [
{"sets": [0], "label": "20Dresses - Shop Women Fashion", "size": 4857},
{"sets": [1], "label": "com.stylecracker.android", "size": 24},
{"sets": [2], "label": "com.shopping.limeroad", "size": 578},
{"sets": [3], "label": "com.craftsvilla.app", "size": 291},
{"sets": [4], "label": "com.voonik.android", "size": 430},
{"sets": [0, 1], "size": 24},
{"sets": [0, 2], "size": 578},
{"sets": [0, 3], "size": 291},
{"sets": [0, 4], "size": 430},
]
我不明白我怎样才能实现上述结构。任何帮助都将受到高度赞赏。
由于
答案 0 :(得分:1)
它只需要一些基本的转换
// considering array is your initial array;
var singleItems = [];
var intersections = [];
var vennSets;
array.forEach(function(item, index) {
singleItems.push({
sets: [index],
label: item.package || item.competingapps,
size: item.total
});
if (item.competingapps) {
intersections.push({
sets: [0, index],
size: item.total
});
}
});
vennSets = singleItems.concat(intersections);
您可能希望坚持使用更多功能转换方式,以避免外部范围受到临时变量(singleItems
和intersections
)的污染;
var result = array.reduce(function(prev, item, index) {
prev.push({
sets: [index],
label: item.package || item.competingapps,
size: item.total
});
if (item.competingapps) {
prev.push({
sets: [0, index],
size: item.total
});
}
return prev;
}, []).sort(function(a, b) { return a.sets.length < b.sets.length; });