Home > Blockchain >  Assign values through all of the object properties in typescript
Assign values through all of the object properties in typescript

Time:09-14

I have specific object in my Pinia store

showDeliveryLinesOptions: undefined as
      | undefined
      | {
          options: {
            title: boolean;
            orderStatus: boolean;
            expectedDelivery: boolean;
            price: boolean;
            quantity: boolean;
            totalPrice: boolean;
          };
          deliveryId: string | undefined;
        }[]

and I want to assign an array of showDeliveryLinesOptions as it will have specific deliveryId and all of the options object properties set to false. For now, I have this hard-coded assignment:

    detailsStore.showDeliveryLinesOptions = detailsStore.deliveries.map(
      (delivery) => {
        return {
          deliveryId: delivery.DeliveryId,
          options: {
            expectedDelivery: false,
            orderStatus: false,
            price: false,
            quantity: false,
            title: false,
            totalPrice: false,
          },
        };
      }
    );

But I would like to make it more flexible and iterate through the all of options keys instead of writing all keys and assign false values x times like it is for now. How can I make it happen in typescript?

CodePudding user response:

You could use reduce method with Object.keys to set the options properties to false :

 detailsStore.showDeliveryLinesOptions = detailsStore.deliveries.map(
      (delivery) => {
        return {
          deliveryId: delivery.DeliveryId,
          options: Object.keys(delivery.options).reduce((acc,curr)=>{
                        return {...acc,[curr]:false},
                      },{})
        };
      }
    );

Example

let options = {
  expectedDelivery: true,
  orderStatus: true,
  price: false,
  quantity: true,
  title: true,
  totalPrice: true,
}

let initOptions = Object.keys(options).reduce((acc, curr) => ({ ...acc,
  [curr]: false
}), {})

console.log(initOptions)

  • Related