Home > Software design >  How to use spread operator in javascript?
How to use spread operator in javascript?

Time:04-13

Hi i have code like below,

async createItem(params: ItemParams, id?: any): Promise<Item> {
    const { ...fields } = params; //remove spread operator here
    try {
        const { data: any} = await this.post(`/${ITEM}/`, keysToSnakeCase(fields)); //how can i rewrite this
        //some logic
    }
}

now i want to remove spread operator in line

const { ...fields } = params;

how can i do this. I have tried,

const {fields } = params; // says fields doesnt exist on params error.

could someone help me with this. thanks

CodePudding user response:

The ...fields part could be redundant in this scenario. The spread operator takes all the remaining key value pairs in your object and assigns them to a new object.

In your case fields is by value identical to params.

(Note: fields and params are equal by value, not by reference.)

You can simply rewrite your code like this:

async createItem(params: ItemParams, id?: any): Promise<Item> {
    try {
        const { data: any} = await this.post(`/${ITEM}/`, keysToSnakeCase(params));
        //some logic
    }
}

if the keysToSnakeCase function modifies its properties you'll notice that your original params object changes.

If this is the case, you can add the spread operator back over there to create a shallow clone of the params object so it is not updated.

async createItem(params: ItemParams, id?: any): Promise<Item> {
    try {
        const { data: any} = await this.post(`/${ITEM}/`, keysToSnakeCase(...params));
        //some logic
    }
}

For more info on the spread syntax, please refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

  • Related