Skip to content Skip to sidebar Skip to footer

How To Push Array To Json Object In Angular

I have an obj like below let obj = {staff_changes: []}; Here are some test cases: test case --> success for (let i = 0; i < 4; i++) { obj.staff_changes.push({ id: 'sta

Solution 1:

You need this piece of code -

for (let i = 0; i < 4; i++) {
 obj.staff_changes.push({
  id: i,
  key: {
   id: 'staff'+i
  }

 });
}

Solution 2:

You should define newStaff as an array variable to push data. And also you have missed to define the key name inside the array object.

try this

let obj = {staff_changes: []};
let newStaff=[];
for (let i = 0; i < 4; i++) {
 newStaff.push({id: 'staff' +i});
 obj.staff_changes.push({
  id: i,
  newStaff: newStaff
 });
}
console.log(obj);

Solution 3:

newStaff variable not found in test case 2, declare newStaff inside for loop

let obj = {staff_changes: []};

for (let i = 0; i < 4; i++) {
let newStaff=[];
 obj.staff_changes.push({
  id: i,
  newStaff:newStaff.push({
   id: 'staff'+i
  });

 });
}

console.log(obj);

Post a Comment for "How To Push Array To Json Object In Angular"