【问题标题】:I want to create an array with number of objects that is equal to the number of obj in plants array我想创建一个对象数量等于植物数组中 obj 数量的数组
【发布时间】:2021-08-11 12:19:38
【问题描述】:

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',
    //       }
    //     ]
    //   }
    // ]

感谢任何帮助

【问题讨论】:

  • 为什么预期的和实际的输出被不必要地注释了?
  • 标题是什么"我想创建一个包含多个对象的数组...""...对象值发生变化所有索引,如何用当前索引限制它” 在问题的正文中?
  • 请添加大括号结束loop函数。 chunk 函数中有什么?

标签: javascript arrays typescript


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多