1

I have been using

      <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
      </FormGroup>

to get a unique array for a dropdown option, however I now need to pass an array with each object in it having a label and a value.

I have refactored the code as follows,

   <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => {
            return {value: options.campaign, label: options.campaign };
          }))]}/>
      </FormGroup>

...but the unique element is now not working (see below with duplicates). What am I doing wrong please?

The input array looks like...

    [
    1. 0:{_id: "zWTiLEjqrCKdxTvze", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "newevent", …}
    2. 1:{_id: "SkZzDMAWokFFYEycp", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "instagramlaunch", …}
    3. 2:{_id: "p4pychanC5Zw8iWAQ", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "stuffinhere", …}
       … more in here including more than 1 object with instagram launch for example
    ]

Original approach resulted in Array of...

    0:"newevent"
    1:"sheffieldevent"
    2:"stuffinhere"
    3:”instagramlaunch"
    4:”anothertest"
    5:”yetanother"

now results in...

    0:{value: "newevent", label: "newevent"}
    1:{value: "sheffieldevent", label: "sheffieldevent"}
    2:{value: "stuffinhere", label: "stuffinhere"}
    3:{value: "instagramlaunch", label: "instagramlaunch"}
    4:{value: "instagramlaunch", label: "instagramlaunch"}
    5:{value: "instagramlaunch", label: "instagramlaunch”}
    6:{value: "anothertest", label: "anothertest”}
    7:{value: "yetanother", label: "yetanother"}
Nick Wild
  • 395
  • 1
  • 6
  • 18

2 Answers2

0
new Set(this.props.records.map(options => {
    return {value: options.campaign, label: options.campaign };
})) 

Does not work, because every new object is a unique object and Set works with all types. As result, you get all options, but not unique options.

If you have the same pattern as you want, you could render the set after collecting all values and build a new objects array out of the set.

var optionsSet = new Set(array.map(option => option.campaign)),
    options = Array.from(optionsSet, v => ({ value: v, label: v }));
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

I resolved this using lodash...

    campaignOptions={_.uniqBy(this.props.records.map((options,index) => {return { value: index, label: options.campaign }}),'label')}/>
Nick Wild
  • 395
  • 1
  • 6
  • 18