当应该推送第二个元素时,json键会被分配一个数字而不是数组

json key gets assigned a number instead of array when second element is supposed to be pushed

本文关键字:分配 一个 数字 数组 第二个 元素 json      更新时间:2023-09-26

我正在尝试生成一个JSON对象,我希望它看起来像这样:

{
 "sreddy-vm-1":["MyDatabase-1"],
 "sreddy-vm-2":["MyDatabase-2"], 
 "sreddy-vm-3":["MyDatabase-3", "MyDatabase-4", "MyDatabase-5"]
} 

但它产生的是

{"sreddy-vm-1":["MyDatabase-1"],"sreddy-vm-2":["MyDatabase-2"], "sreddy-vm-3":3}

生成正确的json,直到每个键在数组中有一个元素的点,第二个元素被添加到sreddy-vm-3的数组时,它分配2,然后在下一个(最后一个(循环中,它最终分配3。我搞不清楚发生了什么。我对Javascript一般来说都是新手。请帮忙。非常感谢。

代码

// part of the code
$scope.forests = ["MyDatabase-1", "MyDatabase-2", "MyDatabase-3", "MyDatabase-4", "MyDatabase-5"];
$scope.forestsOnHosts = {};
angular.forEach($scope.forests, function(forest, key){
    $scope.forestsOnHosts[host] = function () {
        if ($scope.forestsOnHosts[host] === undefined || $scope.forestsOnHosts[host] === null) {
            console.log('******************');
            return new Array(forest);
        } else {
            console.log(JSON.stringify($scope.forestsOnHosts[host]));
            var arr = new Array($scope.forestsOnHosts[host]);
            return arr.push(forest);
        }
    }.call();
}
console.log(JSON.stringify($scope.forestsOnHosts));
return arr.push(forest);

这不会像您所期望的那样返回一个数组。

arr.push(forest);
return arr;