Jose the hose
Jose the hose

Reputation: 1895

Pushing a javascript object into another javascript object

I am trying to merge two javascript sets into one. I am trying to put the products javascript object into the Quotes attribute of the solution object. So the end result should be the SolutionProducts object.

$scope.Products = {  
"id":"",
"attributes":{  
  "term":"36"
},
"groups":[  
  {  
     "products":[  
            // list of products
     ]
  }
]
}

$scope.Solution = {  
"SolutionID":"",
"Quotes":[  

]
}



$scope.SolutionProducts = {  
"SolutionID":"",
"Quotes":[  
  {  
     "id":"",
     "attributes":{  
        "term":"36"
     },
     "groups":[  
        {  
           "products":[  
                  // list of products
           ]
        }
     ]
  }
]
}

I tried to use the push function but it didn't work

$scope.SolutionProducts = $scope.Solution.Quotes[0].push($scope.Products.products);

Upvotes: 0

Views: 83

Answers (2)

Shrey Gupta
Shrey Gupta

Reputation: 5617

@MVP brings up one key issue with your code: you simply want to pass a reference of the Solution object to the SolutionProducts object. With your current code, you are setting $scope.SolutionProducts to the return value of the push() function, which actually returns a the length of the array as an integer, not the object. (See MDN's article on push for more)

The second issue is that you're not actually using push on an array:

$scope.SolutionProducts = $scope.Solution.Quotes[0].push($scope.Products.products);

You're applying .push to Quotes[0], which is a value in the array, not the array itself. You need something like this:

$scope.Solution.Quotes.push($scope.Products);

Now you're using the push function on a proper array.

Putting both of these issues together, you should have something that looks a little like this:

$scope.Solution.Quotes.push($scope.Products);
$scope.SolutionProducts = $scope.Solution; //sets SolutionProducts to Solution reference

Upvotes: 1

Alex
Alex

Reputation: 7833

Simple mistake: you are assigning the return value of the Array.push method to your variable $scope.SolutionProducts. Instead do this:

$scope.Solution.Quotes.push($scope.Products);
$scope.SolutionProducts = $scope.Solution;

Note that $scope.Solution and $scope.SolutionProducts will have the same reference, meaning you actually don't need to have the $scope.SolutionProducts variable and can just go on with $scope.Solution.

Upvotes: 1

Related Questions