-1

After forEach loop the object values changes in all the indexes, how to limit it with the current index

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

But am getting results as

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

Any help is appreciated

DecPK
  • 24,537
  • 6
  • 26
  • 42
FE-Deve
  • 13
  • 3
  • Why are the expected and actual output unnecessarily commented? – Andreas Aug 11 '21 at 12:26
  • What has the title _"I want to create an array with number of objects..."_ to do with the _"...the object values changes in all the indexes, how to limit it with the current index"_ in the body of the question? – Andreas Aug 11 '21 at 12:26
  • [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Andreas Aug 11 '21 at 12:27
  • Please add the curly bracket to end the `loop` function. What is in the `chunk` function ? – Marco Aug 11 '21 at 12:28

1 Answers1

0

Just map over the original plants and use the label.

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

The reason you get that result is that you shallow copy the object, Any change to that variable will affect the original variable.