How to remove an object's property when using the spread operator in order to create a new instance of an object?

1813 views typescript
0

Given these two Interfaces:

interface IFoo {
    foos: string[];
    fnord: string;
}

interface IFooFlat {
    foo: string;
    fnord: string;
}

I want to convert an array of IFoo into IFooFlat via this map function:

const foos: IFoo[] = [
    {
        foos: [
            "narf",
            "poit"
        ],
        fnord: "fnord"
    }
];

const flattened: IFooFlat[][] = foos.map((fooObject: IFoo): IFooFlat[] => {
    fooObject.foos.map((fooItem: string): IFooFlat => {
        return {
            ...fooObject,
            foo: fooItem,
        };

    });
});

Yet this will generate the error:

Type '{ foo: string; foos: string[]; fnord: string; }' is not assignable to type 'IFooFlat'.
  Object literal may only specify known properties, and 'foos' does not exist in type 'IFooFlat'.

I now want to remove the foos property yet I do not want to apply each property explicitly (my real world case example has many more properties), I only want to delete a very specific property, namely foo.

Hence, I tried creating a clone and deleting the property, yet it fails while throwing the same error:

const flattened = foos.map((foosObject: IFoo): IFooFlat[] => {
    const clone = Object.assign(foosObject, {});
    delete clone.foos;

    return foosObject.foos.map((oneFooString: string): IFooFlat => {
        return {
            ...clone,
            foo: oneFooString,
        };
    });
});

How can I delete a property from an object in TypeScript?

answered question

1 Answer

0

You can combine the destructuring syntax with the spread-operator to achieve what you want:

const flattened = foos.map((foosObject: IFoo): IFooFlat[] => {
    const { foos, ...clone } = foosObject; // clone will contain all properties but `foos`.

    return foos.map((oneFooString: string): IFooFlat => {
        return {
            ...clone,
            foo: oneFooString,
        };
    });
});

console.log(JSON.stringify(flattened, null, 4));

will print:

[
    [
        {
            "fnord": "fnord",
            "foo": "narf"
        },
        {
            "fnord": "fnord",
            "foo": "poit"
        }
    ]
]

posted this

Have an answer?

JD

Please login first before posting an answer.