Different return value

40 Views Asked by At

I have this code block:

        let projectTypes: ProjectType[] = [
            ...realm.objects<ProjectType>('ProjectType')
        ].map((projectType) => {
            const icons = Object.values(
                projectType.icons_stringify ?? {}
            ).map((item) => {
                const parsedItem: MuStatusIconObj = JSON.parse(item);
                const iconUri = createUriFromBase64(
                    parsedItem.base64Data,
                    'png'
                );
                return { ...parsedItem, iconUri };
            });
            projectType.icons = icons;
            return projectType;
        });

And everything works as expected (array of objects with all projectType keys and values + icons array); I get the values as expected. But I just wonder why if I change these two lines:

projectType.icons = icons;
return projectType;

To this:

return { ...projectType, icons }

I get projectTypes as an array of objects with only the 'icons' key and its value (without the keys and values of projectType). Just wondering why it's happening?

1

There are 1 best solutions below

0
Deadbeef Development On

When dealing with class instances, the spread syntax {...object} only copies over the instance's own enumerable properties. It does not copy non-enumerable properties or methods defined on the class's prototype. Specifically, it will not include:

  • Non-enumerable properties: These are properties that are not listed in for...in loops and are not returned by Object.keys() or Object.getOwnPropertyNames().
  • Prototype chain properties: Methods and properties defined on the class (in its prototype) are not copied because the spread syntax only deals with the instance’s own properties.

For example, if you have a class like this:

class ProjectType {
    constructor(icons) {
        this.icons = icons;
    }

    getIcons() {
        return this.icons;
    }
}

And you create an instance and use the spread syntax on it:

let instance = new ProjectType(icons);
let copiedInstance = {...instance};

In copiedInstance, you would get only the icons property and not the getIcons method, because getIcons is on ProjectType's prototype, not directly on the instance object itself.