0

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

1
  • 1
    Please show us valid input and expected output. Commented Nov 26, 2020 at 12:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The dates should be unique cause its from a reduce! will let you know when i get it transcribed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.