Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign values through all of the object properties in typescript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading