简体   繁体   中英

Replace object in array with data from another array's object in JavaScript

Assuming we have 2 arrays:

array1 has 1 event:

var array1 = [
      {
      start: '2018-04-24T10:00:00',
      end: '2018-04-24T11:00:00',
      title: 'Been to Break'
    }
  ];

array2 has 3 events:

  var array2 = [
      {
        start: '2018-04-24T08:00:00',
        end: '2018-04-24T10:00:00',
        title: 'Lunch'
      },
      {
        start: '2018-04-24T10:00:00',
        end: '2018-04-24T11:00:00',
        title: 'Break'
      },
      {
        start: '2018-04-24T13:00:00',
        end: '2018-04-24T14:00:00',
        title: 'Meeting'
      }
    ];

Desired results should be a new array: array3

var array3 = [
  { //event 1
    start: '2018-04-24T08:00:00',
    end: '2018-04-24T10:00:00',
    title: 'Lunch'
  },
  { //event 2
    start: '2018-04-24T10:00:00',
    end: '2018-04-24T11:00:00',
    title: 'Been to Break'
  },
  { //event 3
    start: '2018-04-24T13:00:00',
    end: '2018-04-24T14:00:00',
    title: 'Meeting'
  }
];

You can see from the desired results in array3 that the event 2 in array2 was replaced with the event 1 in array1 since the start and end values are a match.

Can this be done in JavaScript? and what about performance if we have let's say 1000 events to loop through

Thanks

A simplistic approach would be to loop over the update array (array1) to find a match in array2 and replace it if found.

 var array1 = [{ start: '2018-04-24T10:00:00', end: '2018-04-24T11:00:00', title: 'Been to Break' }]; var array2 = [{ start: '2018-04-24T08:00:00', end: '2018-04-24T10:00:00', title: 'Lunch' }, { start: '2018-04-24T10:00:00', end: '2018-04-24T11:00:00', title: 'Break' }, { start: '2018-04-24T13:00:00', end: '2018-04-24T14:00:00', title: 'Meeting' } ]; array1.forEach((evUpdate) => { const matchIndex = array2.findIndex((ev) => ev.start === evUpdate.start && ev.end === evUpdate.end); if (matchIndex > -1) { array2.splice(matchIndex, 1, evUpdate); } }); console.log(array2); 

As per performance, there are a lot of other factors that are unknown. For instance, if this is a runtime operation that happens often but the underlying data is fairly static then why not create and store a resultant in a data store?

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