Mitch
Mitch

Reputation: 1394

AngularJS/JavaScript creating a new object from another object

I have a problem that I've been stuck on for awhile and am looking for some advice.

On my controller I have a Restangular call to my back-end to retrieve some data, which looks like this

Angularjs controller (using Restangular)

Pages.controller('PageContentController', ['$scope', '$routeParams', '$location', 'Restangular', function($scope, $routeParams, $location, Restangular) {

    $scope.id = $routeParams.id;

    Restangular.one('pages', $scope.id).getList('content').then(function(response) {
        $scope.content = response;

        $scope.content = _.forEach($scope.content, function(content) {
            content[content.name] = content.content;
        });
        console.log($scope.content);
    });

}]);

Now when I log out $scope.content I get an array with three objects that look similar to this

Array[3]
    0: Object
        banner_heading: "Services",
        id: 1

    1: Object 
        banner_text: "some banner text",
        id: 2

    2: Object
        banner_img: "services.jpg",
        id: 3

There is a lot more to these objects, but i've simplified it for the question and these are the only properties that I want to get out of the objects.

The banner_heading, banner_text, and banner_img are all properties that were dynamically created in the controller above using the lodash forEach loop.

Now on to what I am trying to accomplish. I need to create one object from this array of objects that looks like this

{
    "banner_heading": {
        "data": "Services",
        "id": 1 
    },
    "banner_text": {
        "data": "some banner text",
        "id": 2 
    },
    "banner_img": {
        "data": "services.jpg",
        "id": 3 
    }
}

Basically in my view I need to be able to output the data like {{ banner_heading }} but I also need to be able to maintain the ids for updating the data with the server side.

I'm not sure how this can be done, I've been puzzling over it for a few hours and would great appreciate any help.

Upvotes: 0

Views: 151

Answers (1)

lucuma
lucuma

Reputation: 18339

I am going to propose a solution that doesn't require grouping or doing anything with the original array data:

Assuming we have this per the question:

 $scope.content = [{ banner_heading: "Services", id: 1}, {banner_text:'some text', id:2}, {banner_img:'service.jpg', id:3}];

We can write a function to pull what we need:

$scope.getData = function(n) {
   // question states lodash is being used
   var row = _.find($scope.content, function(item) {
       return n in item;
   });
   return row[n];
}

$scope.getId = function(n) {
  var row = _.find($scope.content, function(item) {
       return n in item;
   });
   return row.id;
}

And on the view:

{{ getData('banner_text') }}

Here is a demo: http://plnkr.co/edit/eHT42YQTaXWtmpbGwUZB?p=preview

Upvotes: 1

Related Questions