首页 > 解决方案 > 我想创建一个对象数量等于植物数组中 obj 数量的数组

问题描述

forEach循环后所有索引中的对象值发生变化,如何用当前索引限制它

 resp = {
        label:'flowers',
        plants: [
          {
            plantLabel: 'rose',
            plantCode: 'RS',
          },
          {
            plantLabel: 'Jasmine',
            plantCode: 'JAS',
          },
          {
            plantLabel: 'Lotus',
            plantCode: 'LU',
          }
        ]
      };

  loop() {
    let newArray = [];
    let tempResp = this.resp;
    const val = chunk(tempResp.plants, 1);
    console.log(val);
    val.forEach(plant => {
      let pushValue = tempResp;
      pushValue.plants= plant;
      newArray.push(pushValue);
    });
    **//expected 
    // [
    //   {
    //     label:'flowers',
    //     plants: [
    //       {
    //         plantLabel: 'rose',
    //         plantCode: 'RS',
    //       }
    //     ]
    //   },{
    //     label:'flowers',
    //     plants: [
    //       {
    //         plantLabel: 'Jasmine',
    //         plantCode: 'JAS',
    //       }
    //     ]
    //   },{
    //     label:'flowers',
    //     plants: [
    //       {
    //         plantLabel: 'Lotus',
    //         plantCode: 'LU',
    //       }
    //     ]
    //   }
    // ]**

但是我得到的结果是

// [
    //   {
    //     label:'flowers',
    //     plants: [
    //       {
    //          plantLabel: 'Lotus',
    //         plantCode: 'LU',
    //       }
    //     ]
    //   },{
    //     label:'flowers',
    //     plants: [
    //       {
    //          plantLabel: 'Lotus',
    //         plantCode: 'LU',
    //       }
    //     ]
    //   },{
    //     label:'flowers',
    //     plants: [
    //       {
    //         plantLabel: 'Lotus',
    //         plantCode: 'LU',
    //       }
    //     ]
    //   }
    // ]

任何帮助表示赞赏

标签: javascriptarraystypescript

解决方案


只需映射原始植物并使用标签。

let newArray = resp.plants.map((plant) => ({
    label: resp.label,
    plant,
});

你得到这个结果的原因是你浅拷贝了对象,对该变量的任何更改都会影响原始变量。


推荐阅读