我有嵌套数组的以下对象:
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”
答案 0 :(得分:2)
您收到错误是因为$scope.regonal[key]
($scope.regonal
中没有任何属性foo1
和foo2
)属于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;
答案 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 = {}
创建密钥