0

I have a file called events.json which I require then use .map to create my object,

var data = require('./events.json')
var newEventList = data.events.map(events => ({
    id: events.id ,
    name: events.name ,
    venue: events.venue.name
}));

However, sometimes on occasion I get two event.ids which are identical. In these instances the map method creates a duplicate entry in my newEventList object. Can I set a conditional within the map function to skip the 'mapping' of that entry if the ids are identical?

One thing to add is that the duplicates always are consecutive in the events.json so the If statement would only be comparing the previously mapped item.

Thanks for your help.

Bwizard
  • 955
  • 2
  • 15
  • 36

4 Answers4

2

Use _.uniqBy available in lodash (Assuming OP wants a loadash solution)

 var data = require('./events.json');
 var _ = require('lodash')
 var newEventList = _.uniqBy(data.events,'id').map(events => ({
     id: events.id ,
     name: events.name ,
    venue: events.venue.name  
 }));
Malice
  • 1,457
  • 16
  • 32
  • 2 very similar answers here but am going to take this one as I like the way it is all contained in one function. Thanks – Bwizard Dec 19 '17 at 13:57
1

Since you are using lodash, you can use the _.uniqBy function that lets you remove duplicates in an array :

const data = require('./events.json');
const uniqEvents = _.uniqBy(data.events, 'id');
const newEventList = uniqEvents.map(events => 
   id: events.id ,
   name: events.name ,
   venue: events.venue.name
);
Dimitri
  • 8,122
  • 19
  • 71
  • 128
1

Array#map creates an output for every item in the original array, so you can't skip items. You can use Array#reduce instead with a helper dedupe Set. For each item, check if the id is in the Set. If not, add it to the result array, and to the Set.

const data = require('./events.json')
const dedupe = new Set();
const newEventList = data.events.reduce((list, event) => {
  if(!dedupe.has(event.id)) {
    list.push({
      id: event.id ,
      name: event.name ,
      venue: event.venue.name
    });

    dedupe.add(event.id);
  }

  return list;
}, []);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0
var idList = [];
var data = require('./events.json')
var newEventList = data.events.map(events => {
idList.indexOf(events.id) !== -1 return // If id exists, skip
idList.push(events.id); // Else push in list for comparing 
return { // And add obj to array
    id: events.id ,
    name: events.name ,
    venue: events.venue.name
}
});
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43