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

Need Some help to refactor or optimize the code in javascript object

I have tried writing the array of objects using ternary but still I am thinking to refactor the common properties between them if someone could help me with this would be helpful.

   const{address } = A

  data: conditionalValue ? [
        { text: text },
        { building: address },
        { ' ': pincode }
      ]:
      [
        { text: text },
        { building: address },
        { ' ': pincode },
        { 'somevalue': someValue1 },
        { ' ': otherValue},
      ],

still the { text: text },{ building: address },{ ‘ ‘: pincode } objects are same between 2 condition

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 can use some destructuring on a array of additional values:

const conditionalValue = false;
const data = [
  { text: 'text' },
  { building: 'address' },
  { ' ': 'pincode' },
  ...(
    conditionalValue
      ? [{ 'somevalue': 'someValue1' },{ ' ': 'otherValue'}]
      : []
  )
];

console.log(data);

However, I think it might be cleaner to just push your other values into the data array.

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