Search code examples
angularjsobjectprepend

Prepend object key to object in angular controller


I thought this was a javascript problem but I'm not sure.

Say I have an object like this

   var foo = {
        foo1: 'name', 
        foo2: 'name2' 
    }

and when I make a post call with this in angular in the console the post body shows

{foo1: 'name', foo2: 'name2'}

Great, that's all great.

In my backend though let's say the request body needs to be:

{type: {foo1: 'name', foo2: 'name2'}}

Okay, so in angular, I have that type key in $scope.type and the foo object in $scope.foo

I tried to achieve this by just going

$scope.foo = {$scope.type:$scope.foo};

That didn't work, it just said that the '.' in $scope.type wasn't allowed.

So then I tried setting a var type = $scope.type then put

$scope.foo = {type: $scope.foo};

which worked except the response post was the word 'type' and not the actual value itself. What's going on here? why can't I prepend the key $scope.type to my foo object?


Solution

  • You cannot use dynamic values in an objects braces for the name type. Instead you should do something like this:

    var obj = {};
    obj[$scope.type] = $scope.foo;
    $scope.foo = obj;