将多维数组转换为对象数组。嵌套循环与回调

时间:2018-02-25 18:20:25

标签: javascript arrays object transformation

我目前正在研究一个非常流行的JS对象问题:transformEmployeeData。我得到了我的解决方案映射参数数组及其内部数组。我很满意。但是,我第一次尝试解决同样的问题是创建两个循环,嵌套它们并创建我的对象。出于某种原因,这个解决方案并没有给我预期的结果,我想知道为什么会发生这种情况?正如我所说,我的兴趣是要了解JS的工作原理。不仅让我的规格得以运行。谢谢。

这里已有的代码:

    function transformEmployeeData(array) {   
  return array.map(function(outterArr){
        const finalObj = {};
        outterArr.map(function(innerArr){
           finalObj[innerArr[0]] = innerArr[1];
         });
         return finalObj;   }); }

它的返回值(这是预期值):

[ { firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk' },   {
 firstName: 'Mary',
     lastName: 'Jenkins',
     age: 36,
    role: 'manager' } ]

我的第一次尝试(我能理解为什么它没有返回上述值):

    function transformEmployeeData(array) {  
     let finalArr = [];   
const finalObj = {};  
    for(let i = 0; i < array.length; i +=1){
        let outterArr = array[i];
      for (let j = 0; j < outterArr.length; j+=1){
          let innerArr = outterArr[j];
          finalObj[innerArr[0]] = innerArr[1];    
    }   
     finalArr.push(finalObj);   
    }  
     return finalArr; 
    }

它的返回值(奇怪的是......给我):

[ { firstName: 'Mary',
    lastName: 'Jenkins',
    age: 36,
    role: 'manager' },
  { firstName: 'Mary',
    lastName: 'Jenkins',
    age: 36,
    role: 'manager' } ]

原始数据:

var employeeData = [
    [
        ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
    ],
    [
        ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
    ]
];

1 个答案:

答案 0 :(得分:1)

您定义finalObj一次,但您需要多次更新并推送它。由于同一个对象被推入数组,因此所有项都显示在最后一个循环中分配的值。在每次迭代时,创建一个新的finalObj

&#13;
&#13;
function transformEmployeeData(array) {
  const finalArr = [];

  for (let i = 0; i < array.length; i += 1) {
    const finalObj = {};
    const outterArr = array[i];
    
    for (let j = 0; j < outterArr.length; j += 1) {
      const innerArr = outterArr[j];
      finalObj[innerArr[0]] = innerArr[1];
    }
    
    finalArr.push(finalObj);
  }
  return finalArr;
}

const employeeData = [[["firstName","Joe"],["lastName","Blow"],["age",42],["role","clerk"]],[["firstName","Mary"],["lastName","Jenkins"],["age",36],["role","manager"]]];

console.log(transformEmployeeData(employeeData));
&#13;
&#13;
&#13;

您也可以使用for...of代替循环标准:

&#13;
&#13;
function transformEmployeeData(array) {
  const finalArr = [];

  for (const outterArr of array) {
    const finalObj = {};
    
    for (const innerArr of outterArr) {
      finalObj[innerArr[0]] = innerArr[1];
    }
    
    finalArr.push(finalObj);
  }
  return finalArr;
}

const employeeData = [[["firstName","Joe"],["lastName","Blow"],["age",42],["role","clerk"]],[["firstName","Mary"],["lastName","Jenkins"],["age",36],["role","manager"]]];

console.log(transformEmployeeData(employeeData));
&#13;
&#13;
&#13;