user1486133
user1486133

Reputation: 1487

Map an object of properties where some properties do not exist

I currently am utilising Array.map to create a new object containing some data:

const bookList = [{
   name: "Foo",
   id: "1234",
   quantity: 5,
}];

function mapBooks(bookList) {
  return {
    eventName: "ping",
    data: {
      list: {
        books:
          bookList.map(
            ({name, id, quantity }) => ({ name, id, quantity})
          )
      }
      }
    };
  }

mapBooks(bookList);

// Result:
{
  eventName: "ping",
  data: {
      list: {
          books: {
              name: "Foo",
              id: "1234",
              quantity: 5,
          }
      }
  },
}

This is fine in this example, but what happens when one of the items is not in the provided data?

const bookList = [{
   name: "Foo",
   id: "1234",
}];

mapBooks(bookList);

// Result:
{
  eventName: "ping",
  data: {
      list: {
          books: {
              name: "Foo",
              id: "1234",
              quantity: undefined,
          }
      }
  },
}

How can I adjust my map function to simply not return any undefined values? For example I would prefer a result like this:

mapBooks(bookList);

// Result:
{
  eventName: "ping",
  data: {
      list: {
          books: {
              name: "Foo",
              id: "1234",
              // quantity is simply not included
          }
      }
  },
}

Upvotes: 0

Views: 46

Answers (1)

KALrious
KALrious

Reputation: 67

I don't know if i understand the question correctly but you could something like this:

const bookList = {
   name: "Foo",
   id: "1234",
   quantity: 5,
};

function mapBooks(bookList) {
  return {
    eventName: "ping",
    data: {
      list: {
        books:
          bookList.map(
            (book) => ({ ...book})
          )
      }
      }
    };
  }

With the power of destructuring you will only fulled the present option of the object

Upvotes: 1

Related Questions