ReactJS:如何防止array.push中的重复值?

时间:2019-11-11 11:23:09

标签: javascript arrays reactjs ecmascript-6 array-push

当时,在“选择”框中选择一个选项时,其余选项变为多个值。如何防止重复的值?

import Select from 'react-select';
const dataOptions = []; 
class App extends React.Component {
    constructor(props) {
        super(props);
        this.data = [];
        this.getData();
    }
    getData = () => { api.request({url: `/getdata`}).then(res => res.map(el => this.data[el.id] = el.name)) }

    addData = () => {
        const { selectedId } = this.state;
        var datas = this.data;
        console.log(datas);
        datas.map((name, index) => {
            if (!dataOptions.includes(name)) {
                console.log('b4 push:', dataOptions)
                dataOptions.push({ value: index, label: name });
                console.log('aftr push:', dataOptions)
            }
        });
        return (
            <Select options={dataOptions}
            isMulti
            />
        );
    }
}

此语法中发生了错误:

datas.map((name, index) => {
  if (!dataOptions.includes(name)) {
       dataOptions.push({ value: index, label: name });
  }
}); 

控制台结果

[ "data-1", "data-2", "data-3"]

b4 push: [
  {value: 1, label: "data-1"}
  {value: 2, label: "data-2"}
  {value: 3, label: "data-3"}
]

aftr push: [
  {value: 1, label: "data-1"}
  {value: 2, label: "data-2"}
  {value: 3, label: "data-3"}
]

P.S:这里在aftr push中,我已经从下拉菜单中选择了第一个选项;因此,结果如果不应显示在数组值中。

预先感谢...!

1 个答案:

答案 0 :(得分:2)

destructuring语法应类似于

datas.map(({name, index}) => {
      if (!dataOptions.includes(name)) {
           dataOptions.push({ value: index, label: name });
      }
    }); 

此外,您不需要外部数组即可将数据推送到map函数中,因为该函数默认情况下会返回一个数组,您可以像下面这样简单地完成

 let expected_data=datas.map(({name, index}) => {
              if (!dataOptions.includes(name)) {
                 return  { value: index, label: name };// return a value
              }
            }); 

expected_data将包含操作后所需的数据

查看摘要-

let data = [{
  "name": 1,
  "index": 2
}, {
  "name": 11,
  "index": 21
}]

console.log(data.map(({
  index,
  name
}) => {

  return {
    value: index,
    label: name
  }

}))

您最好使用Array.some()来查找

 datas.map((name,index) => { // here index is the iterator
                if(!dataOptions.some(({value,label})=>label==name  ))
            {
                   dataOptions.push({ value: index, label: name });
              }
            });