简体   繁体   中英

Merge two arrays of objects but with uniqueness on a certain key/value

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

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);

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM