Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically add values to a javascript object

I am trying to learn angular, and I have an example code snippet that is the following:

$scope.contents = [{
    name: 'Chris Doe',
    abbreviation: 'Developer',
},{
    name: 'Ann Doe',
    abbreviation: 'Commerce',
},{
    name: 'Mark Ronson',
    abbreviation: 'Designer',
},{
    name: 'Eric Doe',
    abbreviation: 'Human Resources',
},{
    name: 'John Doe',
    abbreviation: 'Commerce',
},{
    name: 'George Doe',
    abbreviation: 'Media',
},{
    name: 'Ann Ronson',
    abbreviation: 'Commerce',
},{
    name: 'Adam Ronson',
    abbreviation: 'Developer',
},{
    name: 'Hansel Doe',
    abbreviation: 'Social Media',
},{
    name: 'Tony Doe',
    abbreviation: 'CEO',
}];

Which works fine, but I want to fetch data from an API and then load the data into the $scope.contents. I have tried the following:

$http(req).success(function(res) {
    console.log(res);
    for (var i = 0; i < res.length; i++) {
        console.log(res[i]);
        //add data into scope contents here .add(res[i])
    }
}).error(function (err) { console.log(err) });

and this works, I am able to loop through the object of data returned from my API, however I cannot figure out the syntax to add the returned data into $scope.contents What is the proper way to do this? Is there a better way to do this? Like making $scope.contents a class and adding the data as a new instance?

like image 396
user4612487 Avatar asked Jul 23 '15 16:07

user4612487


3 Answers

You can use Array#concat:

$scope.contents = $scope.contents.concat(res);

Obviously you first want to make sure that $scope.contents is already an array:

if (! Array.isArray($scope.contents)) {
  $scope.contents = [];
}
$scope.contents = $scope.contents.concat(res);
like image 55
robertklep Avatar answered Nov 18 '22 10:11

robertklep


$scope.contents is an array, so you can push a new object to it.

$http(req).success(function(res) {
    console.log(res);
    for (var i = 0; i < res.length; i++) {
        console.log(res[i]);
        $scope.contents.push(res[i]);
    }
}).error(function (err) { console.log(err) });

It's not obvious from your example what res[i] contains. The above code is assuming that it is already the correct object. If not, take this and place the correct values.

$scope.contents.push({
    name: res[i].name,
    abbreviation: res[i].abbreviation,
}); // example -- change to match your data
like image 2
AndrewR Avatar answered Nov 18 '22 10:11

AndrewR


$scope.contents looks like an array so...

$scope.contents.push(res[i]);
like image 1
WhiteHat Avatar answered Nov 18 '22 11:11

WhiteHat