Array created by .push in a loop is the correct length but only pushing the last element on repeat

前端 未结 1 1357
深忆病人
深忆病人 2021-01-06 13:57

I am referencing a global variable and parsing through it to push items onto a stack and then I return that stack to be used elsewhere. The returned array is the correct len

1条回答
  •  再見小時候
    2021-01-06 14:31

    With obj declared at the beginning of the function, there's only a single object in existence. Each iteration of the loop you change that one object's properties. What you want to do is create a new {} object each iteration of the inner loop.

    for(var param1 in json){
        for(var param2 in json[param1]){
            for(var param3 in json[param1][param2]){
                var obj = {};
                obj.item1 = json[param1][param2][param3][param4];
                obj.item2 = json[param1][param2][param3][param5];
                obj.item3 = json[param1][param2][param3][param6];
                stack.push(obj);
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题