[英](Javascript) Reduce and Unflatten Array
With a nested array of values: 带有嵌套的值数组:
var stagedArray = [
["Spring", "Volleyball", "V"],
["Spring", "Baseball", "V"],
["Fall", "Baseball", "JV"],
["Fall", "Baseball", "V"]
];
Assuming hierarchically position zero of each nested array is the parent, position one being its direct child and position two being a child of position one, what method can I use to reduce and unflatten this array to get an outcome similar to this: 假设每个嵌套数组的位置0都是父级,位置1是其直接子级,位置2是位置1的子级,我可以使用什么方法来缩小和展开该数组以得到类似于以下结果:
var finalList = [
{
season: "Spring",
items: [
{
sport: "Basketball",
items: [
{ division: "V" },
]
}
{
sport: "Volleyball",
items: [
{ division: "V" },
]
}
]
},
{
season: "Fall",
items: [
{
sport: "Baseball",
items: [
{ division: "V" },
{ division: "JV" }
]
}
]
}]
Ideally down the line I would like to create a function to define what position and which label is associated to them dynamically. 理想情况下,我想创建一个函数来动态定义与它们关联的位置和标签。 Many thanks!
非常感谢!
Worked with a colleague on a good starting point, the next steps would be to update this function to work recursively, with varying depths and dynamic labels. 与同事一起工作是一个很好的起点,接下来的步骤将是更新此功能以递归地工作,并具有不同的深度和动态标签。
function getTranformedData(data) {
var transformedData = {};
for (var i = 0, n = stagedArray.length; i < n; i++) {
var sportData = stagedArray[i];
var season = sportData[0];
var typeOfSport = sportData[1];
var teamDivision = sportData[2];
if (!transformedData.hasOwnProperty(season)) {
// Create new season object
transformedData[season] = {
'season': season,
'items': []
};
}
var transformedSportData = {
'sport': typeOfSport,
'items': {
'division': teamDivision
}
};
transformedData[season]['items'].push(transformedSportData);
}
return transformedData;
}
function convertObjectToArrayOfOjects(dataObject) {
var data = []
for (var key in dataObject) {
data.push(dataObject[key]);
}
return data;
}
var stagedArray = [
["Spring", "Volleyball", "V"],
["Spring", "Baseball", "V"],
["Fall", "Baseball", "JV"],
["Fall", "Baseball", "V"]
];
var data = getTranformedData(stagedArray);
data = convertObjectToArrayOfOjects(data);
console.log(data);
/* RESULTING DAT STRUCTURE */
/*
[{
"season": "Spring",
"items": [{
"sport": "Volleyball",
"items": {
"division": "V"
}
}, {
"sport": "Baseball",
"items": {
"division": "V"
}
}]
}, {
"season": "Fall",
"items": [{
"sport": "Baseball",
"items": {
"division": "JV"
}
}, {
"sport": "Baseball",
"items": {
"division": "V"
}
}]
}]
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.