在reactjs中的Array中查找值

时间:2018-05-21 10:24:49

标签: arrays reactjs react-native

我已声明选项为

let options : any[] ;

并使用json响应填充它,我正在使用

<Select.Creatable
                                    ref="newSource_select"
                                    options={this.state.Options}
                                    id="newSource"
                                    value={this.state.newSource}
                                    onChange= {this.updateNewSource}                                       
                                    labelKey="label"
                                    valueKey="value"
                                    placeholder="Select New Source..."
                            />

 options =['value1' : 'value1' ,
          'value2' : 'value2'
          'value3' : 'value3' ]  // options values entered as mentioned ,

当我输入一个不在选项中的值时,它将提供一个创建标签的选项,标签已创建,但是当模态关闭并再次打开时,iam无法立即在选项中查看,输入的选项已显示在选项的选项中。我怎么解决这个

它返回-1,

4 个答案:

答案 0 :(得分:1)

您正在使用的数据输入既不是对象也不是数组。以下代码可能对您有帮助。

对于数组,

 var options =[ 'value1' ,
                  'value2',
                  'value3' ];
    var data = options.filter((val) => val.includes('value1'));

    console.log(data); 

如果数据输入是对象数组,那么

items = [{id: 1, text: 'test words'}, {id: 2, text: 'another test'}];
var data = items.filter(item => item.text === 'test words')
console.log(data); 

答案 1 :(得分:1)

我不认为你的数组真的是options =['value1' : 'value1' , 'value2' : 'value2' 'value3' : 'value3' ],因为这无法编译。您应该收到错误:

Uncaught SyntaxError: Unexpected token :

我认为你想在这里实现的是一个对象?如果是这样,以下是如何做到这一点:

options = {value1: 'value1', value2: 'value2', value3: 'value3'}

然后要查找对象中是否存在该值,只需执行:

options.hasOwnProperty(value1)

答案 2 :(得分:0)

如果你有阵列:

var array = ["a", "b", "c"];

您可以按照说法使用方法indexOf

array.indexOf("a");

当数组中缺少值时,此方法indexOf返回-1。

所以你的数组看起来应该是

options = ["value1", "value2", "value3"]

答案 3 :(得分:-1)

您可以使用以下包含方法:

var array = ["a", "b", "c"];
array.includes("value2")

此方法返回true或false