noway noway - 8 months ago 40
Javascript Question

adding properties to an existing object inside an array

I am picking an array with few object on it from an external file.


app.controller('mycontroller', function($scope, $http) {
.then(function(response) {
$scope.lols =;

This will give me back something like:

$scope.lols = [
prop1: "h1",
prop2: "h2",
prop1: "g1",
prop2: "g2",

Now I want to add a prop3 in each of the objects how should I do it ? If I had the data into my js file I will do it manually but picking the data from an external file...

I have tried simply doing:

app.controller('mycontroller', function($scope, $http) {
.then(function(response) {
$scope.lols =;
$scope.lols.push = [
{prop3: "h3"},
{prop3: "g3"}

But it has not worked...

Thanks for any help or link explain it.



You want prop3 to be a sibling of prop1 and prop2? If so you can do it either hard-coded like:

$scope.lols[0].prop3 = "h3";
$scope.lols[1].prop3 = "g3";

Or in a more dynamic way:

var newProps = ["h3", "g3"];
for (var i = 0; i < $scope.lols.length; i++) {
  $scope.lols[i].prop3 = newProps[i]; // assuming the length of both arrays is the same size;

The problem with your approach: With push you're creating a new index in the array instead of adding your properties to existing indexes.