Skip to content Skip to sidebar Skip to footer

How To Assign Values To Object That Has Similar Keys?

just wanted to avoid if statements is there way to assign values to object if they have similar keys in response instead of checking each object with if ? what could be efficient

Solution 1:

Check this out: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/hasOwnProperty

You could try this approach:

public responsehandler(@Body()data: any): any {
    const response: Idetails = {} as Idetails;
    if (!data.details) {
         returndata;
    }

    for (const key in response.details) {
            if (data.details.hasOwnProperty(key)) {
                    response.details[key] = data.details[key];
            }
    }

    return response;
}

You should check more validations or conditions to make it work for you.

Solution 2:

If your goal is just to avoid if statements, you could rewrite it like so:

// in js (sorry not a ts user)functionresponseHandler(data) {
  return data.details == null ? data : {details: {...data.details}};
}

console.log(responseHandler({details: {primary: {beginningBalance: 0, endingBalance: 1}}}));

console.log(responseHandler({details: {secondary: {beginningBalance: 0, endingBalance: 1}}}));

console.log(responseHandler({noDetails: 'oopsy'}));

Post a Comment for "How To Assign Values To Object That Has Similar Keys?"