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

扶醉桌前 提交于 2019-12-19 04:00:30

问题


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 length but it repeats items of the last element.

var global = {
    "param11": {
        "param21": {
            "param31": {
                "param4": "1",
                "param5": "2",
                "param6": "3",
            },
            "param32": {
                "param4": "4",
                "param5": "5",
                "param6": "6",

            }
        },
        "param22": {
            "param33": {
                "param4": "7",
                "param5": "8",
                "param6": "9",
            }
        }
    },
    "param12": {
        "param23": {
            "param34": {
                "param4": "10",
                "param5": "11",
                "param6": "12",
            },
            "param35": {
                "param4": "13",
                "param5": "14",
                "param6": "15",
            }
        }
    }
};

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

Returned value:

[
    {"param4":"13", "param5":"14", "param6":"15"},
    {"param4":"13", "param5":"14", "param6":"15"},
    {"param4":"13", "param5":"14", "param6":"15"},
    {"param4":"13", "param5":"14", "param6":"15"},
    {"param4":"13", "param5":"14", "param6":"15"}
]

回答1:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/29380018/array-created-by-push-in-a-loop-is-the-correct-length-but-only-pushing-the-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!