0

I have the following object with nesting array:

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

I need to convert it to:

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

The function below iterates through the first element of the object successfully:

$scope.regonal = {};

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

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

    });
});

... but fails on the second with error:

TypeError: Cannot set property 'bar3' of undefined

2
  • where does foo3 magically appear from? Is that a typo? Commented Oct 26, 2015 at 18:54
  • sorry, typo, corrected... Commented Oct 26, 2015 at 18:56

4 Answers 4

2

$scope.regonal is an empty object, that means that the result of $scope.regonal[key] will be undefined. Trying to access $scope.regonal[key]["bar3"] means you try to access and set the key bar3 on undefined.

try this:

$scope.regonal = {};

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

    });
});
Sign up to request clarification or add additional context in comments.

Comments

2

You get error because $scope.regonal[key] (there is not any property in $scope.regonal with keys foo1 and foo2) is undefined, you should set it as empty object,

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>

Comments

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

DEMO

Comments

0

$scope.regonal[key] returns undefined because there is no key named foo1 or foo 2 in regonal. You can create keys by either $scope.regonal[key]={} or $scope.regonal.key={}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.