Home > other >  From an array of objects making an array of subobjects
From an array of objects making an array of subobjects

Time:04-09

I have an array of JavaScript objects in one of my components

@Component(stuff)
export class ComponentName {
  arrayOfObjects = [];
  // stuff
}

in which each object has the keys key1 and key2.

What I would like is to have an array arrayOfSubobjects in ComponentName whose contents are

{
  key1: 'value1',
  key2: 'value2'
}

for each pair of key1 and key2 that reside within the same object in arrayOfObjects.

Moreover, if the value of key1 updates within an object in arrayOfObjects, it has to be reflected in arrayOfSubobjects. Same thing with key2.

Note that arrayOfObjects is subject to losing/gaining objects.

CodePudding user response:

you can use the map method. A Javascript feature that iterates over the given array, works similar to forEach and will return a value at the end of the loop.

let arrayofSubobjects;

reduceTheArray(): void {
   this.arrayofSubobjects = arrayOfObjects.map(ele => {key1: ele.key1, key2: ele.key2});
}

I've declared the arrayofSubobjects as a global variable and used it inside a function to store the filtered value.
Implemented using typescript syntax (tags).




Upvote if helps :P

CodePudding user response:

In order to have the values dynamically update you need to point to the same reference.

I wonder why not just create an interface that only exposes key1, key2 and use the same array.

At any rate, if I understand your requirements I think something like this will work:

interface ComplicatedObject {
    key1: string;
    key2: string;
}

class SubObject {
    private complicatedObject: ComplicatedObject;

    constructor(complicatedObject: ComplicatedObject) {
        this.complicatedObject = complicatedObject;
    }

    get key1(): string {
        return this.complicatedObject.key1;
    }

    get key2(): string {
        return this.complicatedObject.key2;
    }
}

describe('Testing ComplicatedObject -> SubObject', () => {
    it('should update key1 on SubObject when Complicated Object changes', () => {
        const obj: ComplicatedObject = {
            key1: '1',
            key2: '2'
        };

        const sub: SubObject = new SubObject(obj);

        expect(sub.key1).toBe(obj.key1);
        expect(sub.key2).toBe(obj.key2);

        obj.key1 = 'edited';
        obj.key2 = 'edited as well';
        expect(sub.key1).toBe(obj.key1);
        expect(sub.key2).toBe(obj.key2);
    });
});
  • Related