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

beginner how to combine code together Javascript

Hi I just started learning JS. I want to put cart1 and cart2 together.


if (cart1) {
        for (const key in data) {
          main.push({
            id: Math.random().toString(),
            name: data[key].name
            image: data[key].image
            location: data[key].location,
          });
        }
      }

if (cart2) {
        for (const key in data) {
          main.push({
            id: Math.random().toString(),
            name: data[key].name
            image: data[key].image
          });
        }
      }

    

I used ternary operator, but I don’t want cart2 have location property

if (cart2 || cart1) {
        for (const key in data) {
          main.push({
            id: Math.random().toString(),
            name: data[key].name
            image: data[key].image
            location: cart1? data[key].location : "",
          });
        }
      }

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 optionally add a property by adding it to object and spreading it optionally.

... is the spread operator, which will spread all the properties inside { location: data[key].location } object ( there is only one property which is location ), and that happens only if the cards are not a falsy value ( not equal to null or undefined or a value can be falsy like zero for numbers ) the && operator check value to be truthy.

For more resources.
AND operator
Spread operator

if (cart2 || cart1) {
        for (const key in data) {
          main.push({
            id: Math.random().toString(),
            name: data[key].name,
            image: data[key].image,
            ...(cart1 && { location: data[key].location }),
          });
        }
      }
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