codedamn
codedamn

Reputation: 861

How to add property to each object of an array in typescript.?

i need to add property to each object an array . i have searched a lot , got this, but this is AngularJs. I have tried below but not works. Any help appreciated

 export class ThreeComponent implements OnInit {
 people = [];

 ngOnInit() { 
   this.people = [
   {'name': 'person 1', 'product': 'Medicine 1'},
   {'name': 'person 2', 'product': 'Medicine 2'},
   {'name': 'person 3', 'product': 'Medicine 3'},
   ]
  this.people.push({'total' : '2'})
  console.log(this.people)
  }
 }

results look like this:
(4) [{…}, {…}, {…}, {…}]
 0:{name: "person 1", product: "Medicine 1"}
 1:{name: "person 2", product: "Medicine 2"}
 2:{name: "person 3", product: "Medicine 3"}
 3:{total: "2"}
 length:4
 __proto__:Array(0)

expected result should be:
(3) [{…}, {…}, {…}]
 0:{name: "person 1", product: "Medicine 1", "total": "2"}
 1:{name: "person 2", product: "Medicine 2", "total": "2"}
 2:{name: "person 3", product: "Medicine 3", "total": "2"}
 length:3
 __proto__:Array(0)

Upvotes: 17

Views: 69596

Answers (2)

Griva
Griva

Reputation: 1738

NEW ANSWER

You changed your question completely, you should probably make a new question instead of changing the whole concept. Anyway, if you have to add new properties to your data objects, there is high chance that your app is designed wrong.

To add new property you don't use .push() because this is array method, instead you wanted to add new property to all objects. You can do this by using loop for example like this:

for (var i = 0; i < this.people.length; i++) {
    this.people[i].total = 2; // Add "total": 2 to all objects in array
}

or array .map()

this.people.map((obj) => {
    obj.total = 2;
    // or via brackets
    // obj['total'] = 2;
    return obj;
})

Also, if you need to merge objects or add more unknown properties you can use loop or Object.assign();

for (var i = 0; i < this.people.length; i++) {
    // merge objects into one with multiple props
    this.people[i] = Object.assign(this.people[i], {
        total: '2', 
        someProp: 'hello', 
        likePizza: true, 
    });
}

OLD ANSWER

Ecma5 is compatabile for ES6 and looks like you probably don't know what you want to do.

You put your code in ngOnInit so be sure you call your console.log after this event. Your code says you called console.log(people[1].total) outside of your component class so it can't even access this property.

Also you should not mix different types of objects in one array - this is why typescript was made, to avoid having different things in arrays and objects. Later in loop calling element[i].product can casue error becasue your new object has no such property.

export class ThreeComponent implements OnInit {
  people = [];
  // people: Array<YourObjects>; // would be better

 ngOnInit() { 
   this.people = [
     {'name': 'person 1', 'product': 'Medicine 1'},
     {'name': 'person 2', 'product': 'Medicine 2'},
     {'name': 'person 3', 'product': 'Medicine 3'},
   ];
   let newLength = this.people.push({'total' : '2'}); // returns new array length
   console.log(this.people[newLength ].total); // it works in this case
 }

}

.push() returns new array length what is your new element index in this case becasue push adds new elements at the end of array.

Upvotes: 32

ppajer
ppajer

Reputation: 3145

Array.push adds the element to the end of the array, so you would have to access it via people[people.length-1].total

Upvotes: 3

Related Questions