编写一个将一些员工数据从一种格式转换为另一种格式的函数。
论证看起来像这样:
[
[
['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
],
[
['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
]
]
鉴于输入,返回值应如下所示:
[ {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
{firstName: 'Mary', lastName: 'Jenkins', age: 36, role:'manager'}]
我知道这不是最有效的代码,但我仍然无法让新数组包含对象的每次迭代。我也不一定想要一个新阵列。如何将记录为“person”的内容放入数组中,例如示例的输出。
function keyValue (){
var arr3 = [];
var person = {};
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++){
var key = arr[i][j][0];
var val = arr[i][j][1];
person[key] = val;
}
arr3[i] = person;
}
console.log(person) // desired output, but not returned
return arr3; // either only one instance "joe" or 2
// "marys" depending on where I return
}
keyValue(arr)
//console.logged()
{ firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk' }
{ firstName: 'Mary',
lastName: 'Jenkins',
age: 36,
role: 'manager' }
//returned
=> [ { firstName: 'Mary',
lastName: 'Jenkins',
age: 36,
role: 'manager' },
{ firstName: 'Mary',
lastName: 'Jenkins',
age: 36,
role: 'manager' } ]
答案 0 :(得分:0)
您需要为每个阵列创建一个person
对象。在第二个var person = {}
循环
for
循环内移动for
var arr = [
[
['firstName', 'Joe'],
['lastName', 'Blow'],
['age', 42],
['role', 'clerk']
],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
]
function keyValue(arr) {
var arr3 = [];
for (var i = 0; i < arr.length; i++) {
var person = {};
for (var j = 0; j < arr[i].length; j++) {
var key = arr[i][j][0];
var val = arr[i][j][1];
person[key] = val;
}
arr3[i] = person;
}
return arr3;
}
var res = keyValue(arr);
console.log(res);
&#13;
您也可以使用.map()
,for..of
循环
var arr = [
[
['firstName', 'Joe'],
['lastName', 'Blow'],
['age', 42],
['role', 'clerk']
],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
];
var res = arr.map(array => {
var obj = {};
for (var [key, value] of array) {
obj[key] = value
}
return obj
});
console.log(res);
&#13;