JS新手在这里。我正在学习将嵌套数组转换为包含对象的数组。
我的问题:将var outObj = {};
推入outobj{}
后,为什么outArr[]
会变成数组?
(请参阅本文末尾的预期和实际输出)提前感谢您的帮助。
function transformEmployeeData(inArr) {
var outArr = [];
for(var x = 0; x < inArr.length; x++){
var outObj = {}; // The obj that will be stores in outArr[]
var a1 = inArr[x];
//console.log(a1 + '\n');
for(var y = 0; y < a1.length; y++){
outObj[a1[y][0]] = a1[y][1];
//console.log(outObj[a1[y][0]]);
}
outArr.push(outObj);
}
return arr;
}
var arr = [
[
['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
],
[
['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
]
];
console.log(transformEmployeeData(arr));
/*
Expected Output:
[
{firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
{firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]
Actual Output:
[ [ [ 'firstName', 'Joe' ],
[ 'lastName', 'Blow' ],
[ 'age', 42 ],
[ 'role', 'clerk' ] ],
[ [ 'firstName', 'Mary' ],
[ 'lastName', 'Jenkins' ],
[ 'age', 36 ],
[ 'role', 'manager' ] ] ]
*/
答案 0 :(得分:1)
从outArr
函数调用
arr
而不是transformEmployeeData()
return outArr;