使用Set

时间:2017-12-04 08:44:28

标签: javascript arrays reactjs

我一直在使用

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

获取下拉选项的唯一数组,但是我现在需要传递一个数组,其中每个对象都有一个标签和一个值。

我已经重构了以下代码,

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

...但是唯一元素现在不起作用(参见下面的重复项)。我做错了什么?

输入数组看起来像......

    [
    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
    ]

原始方法导致数组......

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

现在导致......

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

2 个答案:

答案 0 :(得分:0)

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

不起作用,因为每个新对象都是唯一对象,Set适用于所有类型。因此,您可以获得所有选项,但不是唯一选项。

如果你有相同的模式,你可以在收集所有值后渲染集合,并从集合中构建一个新的对象数组。

var optionsSet = new Set(array.map(option => option.campaign)),
    options = Array.from(optionsSet, v => ({ value: v, label: v }));

答案 1 :(得分:0)

我用lodash解决了这个问题......

    campaignOptions={_.uniqBy(this.props.records.map((options,index) => {return { value: index, label: options.campaign }}),'label')}/>