1

I have two Javascript arrays of objects with various keys/values.

I'm trying to achieve a new array of objects with selected keys/values from each of the original arrays, but have uniqueness on a specific key/value.

Example:

const startDate = [
   {
    name: 'John', //Don't need this
    Id: 'ae570d88-809b-45b1-bc20-69b569e361ce', //This should be the 'unique' key
    datePosted: '2020-04-04T00:01:20.000Z' //This will be the start date
   }
]

const endDate = [
   {
    name: 'James', //Don't need this
    Id: 'ae570d88-809b-45b1-bc20-69b569e361ce', //This should be the 'unique' key
    datePosted: '2021-04-04T00:01:20.000Z' //This will be the end date
   }
]

const desiredOutput = [
    {
    'ae570d88-809b-45b1-bc20-69b569e361ce': { 
        startDate: '2020-04-04T00:01:20.000Z',
      endDate: '2021-04-04T00:01:20.000Z'
    }
  }
]

const desiredOutput2 = [
    {
     Id: 'ae570d88-809b-45b1-bc20-69b569e361ce',
     startDate: '2020-04-04T00:01:20.000Z',
     endDate: '2021-04-04T00:01:20.000Z'
  }
]

I've tried using the JS spread operator but can't figure out the renaming of the key to startDate/endDate and adding both to the same object within the array based on uniqueness of the 'Id' key.

Either of the two desiredOutputs would work great

VLAZ
  • 26,331
  • 9
  • 49
  • 67
JamMan9
  • 706
  • 2
  • 9
  • 22

2 Answers2

7

You can map over the startDate array and find the endDate based on the Id.

const startDate = [
   {
    name: 'John', //Don't need this
    Id: 'ae570d88-809b-45b1-bc20-69b569e361ce', //This should be the 'unique' key
    datePosted: '2020-04-04T00:01:20.000Z' //This will be the start date
   }
]

const endDate = [
   {
    name: 'James', //Don't need this
    Id: 'ae570d88-809b-45b1-bc20-69b569e361ce', //This should be the 'unique' key
    datePosted: '2021-04-04T00:01:20.000Z' //This will be the end date
   }
]

const desiredOutput = startDate.map((startObj) => {  
  const foundEndDate = endDate.find((endObj) => endObj.Id === startObj.Id);
  
  return {
    Id: startObj.Id,
    startDate: startObj.datePosted,
    endDate: foundEndDate.datePosted,
  };
});

console.log(desiredOutput);
Reyno
  • 6,119
  • 18
  • 27
2

You could take an object with same Id as key and merge the two arrays.

const
    startDate = [{ name: 'John', Id: 'ae570d88-809b-45b1-bc20-69b569e361ce', datePosted: '2020-04-04T00:01:20.000Z' }],
    endDate = [{ name: 'James', Id: 'ae570d88-809b-45b1-bc20-69b569e361ce', datePosted: '2021-04-04T00:01:20.000Z' }],
    result = Object
        .entries(Object.entries({ startDate, endDate }).reduce((r, [k, v]) => {
            v.forEach(o => r[o.Id] = { ...r[o.Id], [k]: o.datePosted })
            return r;
        }, {}))
       .map(a => Object.fromEntries([a]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392