如何以角度将数组推送到JSON对象(How to push array to JSON object in angular)

248 IT屋

I have an obj like below

let obj = {staff_changes: []};

Here are some test cases:

  1. test case --> success

    for (let i = 0; i < 4; i++) {
     obj.staff_changes.push({
      id: 'staff'+i
     });
    }
    
  2. test case --> failed

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

In test case 2, I'm trying to push an array with name 'newStaff' even it is not present in obj.

In console obj with 4 items is displaying but 'newStaff' is not pushing to obj.

解决方案

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);

我有一个下面的obj



  let obj = {staff_changes:[]}; 


以下是一些测试用例:




  1. 测试用例->成功



     为(令i = 0; i< 4; i ++){
    obj.staff_changes.push({
    id:'staff'+ i
    });
    }

  2. 测试用例->失败



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

    });
    }
    console.log(obj);



在测试案例2中,我正在尝试



在控制台中,有4个项目的obj正在显示,但'newStaff'并没有推送到obj。


解决方案

newStaff 在测试用例2中找不到变量,声明<$在$code>内的$ c $ newStaff 循环



  let obj = {staff_changes:[]}; 

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

});
}

console.log(obj);

本文地址:IT屋 » 如何以角度将数组推送到JSON对象