-3

I have a node/express/mongoose project where I'm not getting something...

I have an endpoint where I'm passing in an object, to populate another object.

The first object may not have all the values needed to populate the new object.

I've tried a number of ways to check each field and if there isn't a matching field in the req.body, then just add a '' to it.

So here is the object I'm trying to build:

    var share = {
          facebook: {
            item: req.body.facebook.item, 
            _id: req.body.facebook._id
          },
          linkedin : {
            item: req.body.linkedin.item,
            _id: req.body.linkedin._id
          },
          google: {
            item: req.body.google.item,
            _id: req.body.google._id
          }

    };

and let's say the object I'm passing in looks like this:

    var share = {
          facebook: {
            item: req.body.facebook.item, 
            _id: req.body.facebook._id
          },
          google: {
            _id: "5c18929c75727bad4144c0a8"
          }

    };

As you can see, 'linkedin' is missing all together, and 'google' is missing the 'item' field.

How do I check to see if a field is missing, then populate it with '_blank' fields so I keep the structure of the object the way I need it to be?

Otherwise, I end up with the dreaded: error: "Cannot read property 'item' of undefined" returned.

Thanks!

cnak2
  • 1,711
  • 3
  • 28
  • 53
  • Look at `lodash` may be.. https://stackoverflow.com/a/41474728/1556857, you can have a "skeleton" object with default values as you wish, and them deep merge it with what you have. It will override the default values where possible, and leave missing values as default. But generally speaking this question is most likely duplicate of many similar questions. – muradm Dec 19 '18 at 06:33

1 Answers1

0

Try to map the object and check if this property is set if it is not then fill it with blank.

VasilisK
  • 19
  • 5