0

Here is an example:

class ExampleClass {
    private x: number;
    private ary: number[];

    constructor(x, ary = []) {
        this.x = x;
        this.ary = ary;
    }

    public getX() {
        return this.x;
    }

    public setX(x) {
        this.x = x;
    }
}

const elemArray = [new ExampleClass(10, [10, 20]), new ExampleClass(20, [20, 30])];

I want to set the elemArray's second element's x to 30 using the setX function. The simplest way would be:

const newElemArray = update(elemArray, {1: {$apply: function (x: ExampleClass) {
    const y = _.cloneDeep(x);
    y.setX(30); 
    return y;
}}});

But I want to be able to do this without cloning the array ary, since that can itself be large and cloning maybe costly. How can I do this?

Thanks

Sagar B Hathwar
  • 536
  • 6
  • 18
  • I think the idea behind immutability is that you can’t alter an object from outside it’s own scope. It seems you are jumping through hoops to get around this, but then why are you using an immutability library? – Kokodoko Jan 02 '19 at 09:23
  • I have an array in redux store, an array of instances. Rather than cloning the entire array, I want to be able to change one field of one item of the array. Any simpler suggestion(not using an immutability library, perhaps?) is welcome – Sagar B Hathwar Jan 02 '19 at 09:43

0 Answers0