I want to add objects to the array (forEach, push)

Asked 2 years ago, Updated 2 years ago, 88 views

I would like to push the object to the array using the sample code below, but I cannot do as I wish.
Push {text:"aaa", imagePath:""} to arry in the first loop using forEach and
I think I'm pushing {text:"bbb", imagePath:"", link:""} to arry in the second loop, but somehow the last console.log(array) will print [{text:"", imagePath:""}, {text:"", imagePath:"].

[{text:"aaa", imagePath:""}, {text:"bbb", imagePath:"] should be printed.
How can I output the desired value?

I'm not sure if it's a problem with how to use forEach, push or react behavior, so
If anyone understands, please let me know.

 Sample code (This is an image of handleClick running when there is an onClick event, although the render part is broken.)

interface Description {
  text:string;
  imagePath:string;
}

const sample:React.FC=()=>{
 const test = React.useRef<Array<string>>();
 const description=React.useRef<Description>();

 handleClick=()=>{
  text.current=["aaa", bbb" ];
  constarray —Array<Description>=[];

  test.current.forEach(function(value,key){
   description.current.text=value;
   console.log(description.current); // The first loop prints {text:"aaa", imagePath:""} and the second loop prints {text:"bbb", imagePath:""}
   array.push(description.current);
  }

  console.log(array); / [{text:\", imagePath:\"}, {text:\", imagePath:\"}] is printed
 }
}

By the way, I tried without using forEach (sample code 2)
[{text:"aaa", imagePath:""}, {text:"bbb", imagePath:""] output.
Also, I tried push with array[index]=description.current although it was not in the sample, but the result was the same.

Sample Code 2
 handleClick=()=>{
  text.current=["aaa", bbb" ];
  constarray —Array<Description>=[];

   description.current.text=test.current[0];
  console.log(description.current); // {text:"aaa", imagePath:""} is printed
   array.push(description.current);

   description.current.text=test.current[1];
   console.log(description.current); // {text:"bbb", imagePath:""} is printed
   array.push(description.current);

  console.log(array); // [{text:"bb", imagePath:""}, {text:"bb", imagePath:""}] is printed
 }

reactjs typescript next.js

2022-09-30 14:37

1 Answers

Self-resolved.

I could have recreated the object before I pushed it.
However, I don't know why it has to be remade, so I would appreciate it if you could let me know if anyone knows.

const data=Object.assign({}, description.current);
array.push(data);


2022-09-30 14:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.