While i’m trying to update the key values of an array of json objects using the values from another array:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { name = 'Angular'; arr = [ { name: 'Rakesh', age: 24 }, { name: 'Ram', age: 26 }, ]; ar = [45, 50]; array = []; ngOnInit() { this.myfunc(); } myfunc(): void { this.arr.forEach((e) => { this.ar.forEach((el) => { e['age'] = el; this.array.push(e); }); }); console.log(this.array); } }
While looping, age is getting updated with each value as in array, but on pushing into the array, the value of key(age) of json objects are getting updated with the last element of the array. How can I make this work?
Below is the output I’m getting:
Output of my code: [{ name: 'Rakesh', age: 50 }, { name: 'Rakesh', age: 50 }, { name: 'Ram', age: 50}, { name: 'Ram', age: 50 },] Expected output: [ { name: 'Rakesh', age: 45 }, { name: 'Rakesh', age: 50 }, { name: 'Ram', age: 45 }, { name: 'Ram', age: 50 } ]
Advertisement
Answer
instead of directly pushing e
, you want to create a new object.
var item = {name: e.name, age: el} this.array.push(item);
otherwise, you are just changing the age
value of e
twice.