angularjs.forEach第二次迭代无法设置对象属性

时间:2015-10-26 18:47:20

标签: javascript arrays angularjs object

我有嵌套数组的以下对象:

var foobar = {
        "foo1": ["bar1", "bar2"],
        "foo2": ["bar3", "bar4"]
        }

我需要将其转换为:

{
    "foo1": {"bar1":"bar1", "bar2":"bar2"},
    "foo2": {"bar3":"bar3", "bar4":"bar4"}
}

下面的函数成功遍历对象的第一个元素:

$scope.regonal = {};

angular.forEach(foobar, function(value, key) {
    angular.forEach(value, function(v) {

        $scope.regonal[key][v] = v;

    });
});

...但第二次失败却出错:

  

TypeError:无法设置未定义的属性“bar3”

4 个答案:

答案 0 :(得分:2)

您收到错误是因为$scope.regonal[key]$scope.regonal中没有任何属性foo1foo2)属于undefined,您应该将其设为空对象,



var foobar = {
  "foo1": ["bar1", "bar2"],
  "foo2": ["bar3", "bar4"]
};

var $scope = {}; // just for example 

$scope.regonal = {};

angular.forEach(foobar, function(value, key) {
  $scope.regonal[key] = {};

  angular.forEach(value, function(v) {
    $scope.regonal[key][v] = v;
  });
});

console.log($scope.regonal);

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

$scope.regonal是一个空对象,表示结果 $scope.regonal[key]将不确定。尝试访问$scope.regonal[key]["bar3"]意味着您尝试访问并设置未定义的键3。

试试这个:

$scope.regonal = {};

angular.forEach(foobar, function(value, key) {
    $scope.regonal[key] = {};
    angular.forEach(value, function(v) {
        $scope.regonal[key][v] = v;

    });
});

答案 2 :(得分:1)

for(key in foobar){
    $scope.regional[key] = foobar[key].reduce(function(obj, curr){
        obj[curr] = curr;
        return obj;        
    },{});    
}

DEMO

答案 3 :(得分:0)

$ scope.regonal [key]返回undefined,因为在regonal中没有名为foo1或foo 2的键。您可以通过$ scope.regonal [key] = {}或$ scope.regonal.key = {}

创建密钥