简体   繁体   English

JS - 我不明白为什么这个对象声明不起作用

[英]JS - I don't understand why this declaration of object doesn't work

I'm just starting out learning some JS and I have a very simple but confusing question.我刚刚开始学习一些 JS,我有一个非常简单但令人困惑的问题。 I've tried to debug my code to see how this works and why it works the way it does but I just don't get it.我试图调试我的代码以查看它是如何工作的以及为什么它会以这种方式工作,但我就是不明白。 Below I have my function along with a sample input of employeeData .下面我有我的函数以及employeeData的示例输入。

function transformEmployeeData(employeeData) {
  var result = [];
  var obj = {};
  for (var i = 0; i < employeeData.length; i++) {
    for (var j = 0; j < employeeData[i].length; j++) {
      obj[employeeData[i][j][0]] = employeeData[i][j][1];
    }
    result.push(obj);
  }
  return result;
}

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

/* Expected Results -
[
    {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
] 

Actual Results - 
[
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'},
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]*/

I know how to fix my code to get the desired results by moving the var obj = {};我知道如何通过移动var obj = {};来修复我的代码以获得所需的结果var obj = {}; line right after the for loop of i .紧跟在ifor循环之后的一行。 What I don't understand is why does the above code not work?我不明白的是为什么上面的代码不起作用? After the i = 0 finishes, the obj holds the first expected input and pushes it into the result array.i = 0完成后,obj 保存第一个预期输入并将其推送到结果数组中。 But then it pushes the Mary array and over writes the rest and I end up with the actual result.但随后它推送 Mary 数组并覆盖其余部分,我最终得到了实际结果。 Couple of questions.几个问题。 Why does my initial object that is correct holding data of Joe disappear from my array and why does the object holding the Mary data get put in twice?为什么我的正确保存Joe数据的初始对象从我的数组中消失,为什么保存Mary数据的对象被放入两次? If I'm understanding my code correctly;如果我正确理解我的代码; the for loop for i should only iterate twice meaning that there should only ever be two objects pushed into it but why do I end up with 2 Mary objects inside? for循环 for i应该只迭代两次,这意味着应该只推入两个对象,但为什么我最终会在里面有 2 个Mary对象? And lastly why does the declaration of a new object variable need to be inside the initial for loop?最后,为什么新对象变量的声明需要在初始for循环内?

Since you are learning, here is my 2c to your learning journey.由于您正在学习,因此这是我对您的学习之旅的 2c。 Instead of endless nested loops, try to embrace the gems of functional programming, namely, Array.prototype.map and Array.prototype.reduce .尝试拥抱函数式编程的精华,即Array.prototype.mapArray.prototype.reduce ,而不是无休止的嵌套循环。 Using them, you can achieve what you were doing in a much more elegant (and often times, faster) manner:使用它们,您可以以更优雅(通常更快)的方式实现您正在做的事情:

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

var transformedInput = input.map(function(el) {
    return el.reduce(function(result, elel) {
        result[elel[0]] = elel[1];
        return result;
    }, {});
})

Your code has only one mistake otherwise it is ok,你的代码只有一个错误,否则没关系,

JavaScript Objects are passed by reference , but you are pushing the same Object in every iteration, so the next object overrides the last one and you got the same object in all iteration. JavaScript 对象是通过引用传递的,但是您在每次迭代中都推送相同的对象,因此下一个对象会覆盖上一个对象,并且您在所有迭代中都获得了相同的对象。

So what you have to do is declare var obj;所以你要做的就是声明var obj; outside the loop and put the obj = {};循环外并放置obj = {}; inside the first for loop, so that a new object is created each time loop iterates ,在第一个 for 循环内,这样每次循环迭代时都会创建一个新对象

See my below working example:请参阅我的以下工作示例:

 function transformEmployeeData(employeeData) { var result = []; var obj; for (var i = 0; i < employeeData.length; i++) { obj = {}; for (var j = 0; j < employeeData[i].length; j++) { obj[employeeData[i][j][0]] = employeeData[i][j][1]; } result.push(obj); } return result; } var input = [ [ ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk'] ], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ] console.log(transformEmployeeData(input));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM