Home > Mobile >  How to save the name of object in array object?
How to save the name of object in array object?

Time:06-22

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!

CodePudding user response:

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('');

  • Related