我想创建一个输出数组,它从子数组中获取所有参数并创建一个结果数组。 难以用语言解释,所以我将通过下面的例子进行解释。
var myArr=[
{
"Id":1,
"Name":'Ken',
"Age" : '30',
"Hobbies" : [{'HobbyId':1,'HobbyName':'Swimming'},{'HobbyId':2,'HobbyName':'Reading'}],
"Skills" : [{'SkillId':1,'SkillName':'PHP'},{'SkillId':2,'SkillName':'MySQL'}],
"Language" : [{'LangId':2,'LangName':'English'},{'LangId':3,'LangName':'Chinese'}]
},
{
"Id":2,
"Name":'Mike',
"Age" : '20',
"Hobbies" : [],
"Skills" : [],
"Language" : []
},
{
"Id":3,
"Name":'Charlie',
"Age" : '25',
"Hobbies" : [{'HobbyId':5,'HobbyName':'Dance'},{'HobbyId':6,'HobbyName':'Sing'},{'HobbyId':7,'HobbyName':'Writing'}],
"Skills" : [],
"Language" : [{'Id':7,'Name':'English'}]
}
]
在上面的例子中,有3个名为Hobbies,Skills and Languages的子阵列。 除了这三个之外,我还会有更多的子阵列。 我实际上想要删除子阵列逻辑并使其成为一个扁平数组。
因此,在创建这个平面数组时,即使子数组为空,我也要考虑子数组中的所有参数。 所以我的结果数组的第一项将包含所有子数组的第一项,依此类推。 即使子数组是一个空数组,我也需要考虑键并将值输入为空。
所以我得到的数组如下:
var resultArray = [
{
"Id":1,
"Name":'Ken',
"Age" : '30',
"HobbyId" : 1,
"HobbyName" : 'Swimming',
"SkillId" : 1,
"SkillName":'PHP',
"LangId" : 2,
"LangName" : 'English'
},
{
"Id":1,
"Name":'Ken',
"Age" : '30',
"HobbyId" : 2,
"HobbyName" : 'Reading',
"SkillId" : 2,
"SkillName":'MySQL',
"LangId" : 3,
"LangName" : 'Chinese'
},
{
"Id":2,
"Name":'Mike',
"Age" : '20',
"HobbyId" : '',
"HobbyName" : '' ,
"SkillId" : '',
"SkillName":'',
"LangId" : '',
"LangName" : ''
},
{
"Id":3,
"Name":'Charlie',
"Age" : '25',
"HobbyId" : 5,
"HobbyName" : 'Dance',
"SkillId" : '',
"SkillName":'',
"LangId" : 7,
"LangName" : 'English'
},
{
"Id":3,
"Name":'Charlie',
"Age" : '25',
"HobbyId" : 6,
"HobbyName" : 'Sing',
"SkillId" : '',
"SkillName":'',
"LangId" : '',
"LangName" : ''
},
{
"Id":3,
"Name":'Charlie',
"Age" : '25',
"HobbyId" : 7,
"HobbyName" : 'Writing',
"SkillId" : '',
"SkillName":'',
"LangId" : '',
"LangName" : ''
}
]
答案 0 :(得分:0)
这似乎产生了你想要的东西:
let results = [];
for(let {Id, Name, Age, Hobbies, Skills, Language} of myArr) {
let numRows = Math.max(1, Hobbies.length, Skills.length, Language.length);
for (let i=0; i<numRows; i++) {
let {HobbyId, HobbyName} = Hobbies[i] || {};
let {SkillId, SkillName} = Skills[i] || {};
let {LangId, LangName} = Language[i] || {};
results.push({
Id, Name, Age,
HobbyId, HobbyName,
SkillId, SkillName,
LangId, LangName,
});
}
}
console.table(results);
非平凡的比特是:
for..of
。Hobbies[i] || {}
以确保我总是有一个使用let {HobbyId, HobbyName}
进行解构的对象。我这样做是因为它比每次检查null
更简单。