3

I have an array containing 7 objects named is NewClass.

enter image description here

When I make some changes to the objects, the object has lost its original NewClass name.

Like that:

enter image description here

In arrray[6] lost NewClass name.

So is there any way I can keep the NewClass name for that object?

Here is my function to handle this array:

useEffect(() => {
console.log(layers);
if (selectedLayerIndex && layers.length > 0) {

  console.log(
    'x',
    layers.map((x) => {
      if (x.feature.properties.editLayerId === selectedLayerIndex) {
        console.log(x);

        return (x = {
          ...x,
          options: { ...x.options, color: 'cyan', fillColor: 'cyan' },
        });
      }
      return x;
    })
  );
  
}

}, [selectedLayerIndex]);

Thank you so much!

3
  • @brk I have updated my code above. Please help me if you can. Thank you. Commented Jun 22, 2022 at 4:01
  • share the response also Commented Jun 22, 2022 at 4:06
  • @brk About the response is an array of objects similar to that because inside each object contains a lot of properties I can't copy it all out. The important thing is that I just want to save the name of the object as NewClass even if it changes the internal properties of that class. That photo, in my opinion, is really clear. If you can help me thank you for that otherwise I will wait for other answers or find solutions myself. Thank you. Commented Jun 22, 2022 at 4:16

1 Answer 1

2

by using the syntax x = {...x, option: {/* some changes to the class */} here, you change the class to a object, which cause a lost of your class name.

If you want to keep it as a class, please use instance.attribute instead, see the following example

class Demo {
    constructor(color){
        this.color = color;
    }
}

var array = [new Demo('red'),new Demo('red'),new Demo('red'),new Demo('red'),new Demo('red'),new Demo('red'),new Demo('red')];

console.log('original array', array);
console.log('');

array[6] = {...array[6], color: 'blue'};
console.log(array); // array[6] have been change to a object
console.log('');

array[5].color = 'green';
console.log(array); // array[5] is still a class
console.log('');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.