使用嵌套的值数组:
var stagedArray = [
["Spring", "Volleyball", "V"],
["Spring", "Baseball", "V"],
["Fall", "Baseball", "JV"],
["Fall", "Baseball", "V"]
];
假设每个嵌套数组的层次位置为父,第一个位置是其直接子节点,第二个位置是第一个位置的子节点,我可以使用什么方法来减少和取消此数组以获得类似于此的结果:
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" }
]
}
]
}]
理想情况下,我想创建一个函数来定义哪个位置以及哪个标签动态地与它们相关联。 非常感谢!
答案 0 :(得分:0)
在一个良好的起点上与同事合作,接下来的步骤是更新此功能,以递归方式工作,具有不同的深度和动态标签。
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"
}
}]
}]
*/