Search code examples
javascriptecmascript-6conditional-operator

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


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.