您还可以使用纯 JavaScript 重新组织数据,如下所示:
var flat_data = [];
var all_keys = []
var data_by_cat = {};
for (var i = 0; i < main.length; ++i) {
var item = main[i];
// check if you already saved that key
if (all_keys.indexOf(item['key']) == -1) {
all_keys.push(item['key']);
// you also need to add a new key to data_by_cat
data_by_cat[item['key']] = [];
}
// append all data to flat_data and data_by_cat
for (var j = 0; j < item['data'].length; ++j) {
flat_data.push(item['data'][j]);
data_by_cat[item['key']].push(item['data'][j]);
}
}
然后你得到你的所有data
元素flat_data
,键的列表all_keys
和一个字典,你的键作为键,每个类别的所有数据的数组作为一个值,如下所示:
var flat_data = [
"img/icon1.png",
"img/icon2.png",
"img/icon3.png",
"img/icon1.png",
"img/icon2.png",
"img/icon3.png",
"img/icon1.png",
"img/icon2.png",
"",
"",
"img/icon1.png"
];
var all_keys = [
"all",
"cat1",
"cat2",
"cat3",
"cat4",
"cat5"
];
var data_by_cat = {
"all": [
"img/icon1.png",
"img/icon2.png",
"img/icon3.png"
],
"cat1": [
"img/icon1.png",
"img/icon2.png",
"img/icon3.png"
],
"cat2": [
"img/icon1.png",
"img/icon2.png"
],
"cat3": [
""
],
"cat4": [
""
],
"cat5": [
"img/icon1.png"
]
};