Mickey Gray
Mickey Gray

Reputation: 460

Mapping Array Of Objects By Key

I have two arrays created from a reduce method that searches two existing arrays for dates. It then turns those dates into unique object keys.

The first group is a list of names the second is a set of series of instructions.

The goal is to combine the two arrays that get formed by finding like object keys and adding the matching list object and insert it into the set of instructions with the object key list.

For one it makes an array that looks like :

const listObj = [
  {11/20/2020: [{name:'Joe', date:11/20/2020}]},
  {11/26/2020 : [{name:'John', date:11/26/2020}]}
]

And this:

const scheduleObj = [
  {11/20/2020: {type:'Federal', date:11/20/2020}},
  {11/26/2020 : {type:'State', date:11/26/2020}}
]

The final product that i need would look something like:

const scheduleObj = [
  {11/26/2020 : {
    type: 'State',
    list: [{name:'John', date:11/26/2020}]
  },
  ...
]

Where the list is an added key and the array is the array that is associated with the object key

I have used a messy what looks like lodash method to get this to work, but I figure there has to be some sort of mapping I can do.

Any Help Would Be Appreciated

Upvotes: 0

Views: 642

Answers (1)

Alberto Anderick Jr
Alberto Anderick Jr

Reputation: 1142

This can be little messy and not failure proof depending on what you have in your listObj or scheduleObj. E.g. repeated date in scheduleObj can lead to a problem using this method, you may have to use another key if the dates are no unique in both lists.

scheduleObj.map((s) => {
  // get the first key of the object as the date you're going to group with
  const date = Object.keys(s)[0];

  // filter the object that matches the date
  const listObjFilter = listObj.filter((o) => Object.keys(o)[0] === date);

  // get the list for the given date (or empty array if nothing found)
  const listForDate = listObjFilter.length ? listObjFilter[0][date] : [];

  // build the result object
  return {
    [date]: {
      type: s[date]['type'],
      list: listForDate
    }
  };
})

Note that I'm always considering you have only one key in the objects inside the lists in listObj or scheduleObj.

Upvotes: 1

Related Questions