给定结果为:
var resultdata=[
{'typeName':'type1'},{'valueName':['value1','value2']},
{'typeName':'type2'},{'valueName':['value3','value4']}
]
我将调用 'typeName' 类别和 'valueName' 项目。
由于原始数据是这样的:
var data= [
['typeName', 'valueName'],
['type1', 'value1'],
['type1', 'value2'],
['type2', 'value3'],
['type2', 'value4']
]
很明显有一个模式。第一行数据将用作类别和项目的标签。其余所有数据表示类别和项目中使用的值。
第一步是提取标签:
var categoryLabel = data[0][0];
var itemLabel = data[0][1];
接下来,需要确定唯一类别,因此我们将使用 reduce 来构建唯一类别数组:
var categories = data
.filter(function(row, i) { return i > 0 }) // remove the labels
.reduce(function(arrCategories, currRow) {
// Add the current rows' category if it doesn't already exist
var currCategory = currRow[0];
if (arrCategories.indexOf(currCategory) === -1) {
return arrCategories.concat(currCategory);
}
return arrCategories;
}, [])
现在您有了一组类别,您只需遍历每个类别即可找到属于它的所有项目:
var valuesByCategory = {};
categories.forEach(function(category) {
// find all the data items that match the category
var items = data
.filter(function(row) { return row[0] === category; })
.reduce(function(arrItems, currRow) {
var currItem = currRow[1];
if (arrItems.indexOf(currItem) === -1) {
return arrItems.concat(currItem);
}
return arrItems;
}, []);
valuesByCategory[category] = items;
});
现在所有的数据都已经解析出来了,剩下要做的就是构建结果数组:
var resultdata = [];
// iterate through each of the categories
categories.forEach(function(category) {
// using the category label, output an object with the label and category
var categoryObj = {};
categoryObj[categoryLabel] = category;
resultdata.push(categoryObj);
// Next, create a items object containing all the values
var itemsObj = {};
itemsObj[itemLabel] = valuesByCategory[category];
resultdata.push(itemsObj);
}
就是这样:)
最好的部分是您不需要任何外部库。这都是 ES2015 javascript!