find a value in a Array in reactjs

I have Declared options as

let options : any[] ;

and populated it using json response , I am using

<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 ,

When i enter a value which in not in the options , it will provide a option to create a tag , tag is been created , but iam not able to view it in the options immediately , when the modal is closed and opened again , the entered option in been showed in the options of select . how can i resolve this

it is returning -1 ,

Upvotes: 0

Views: 29681

Answers (4)

hamid reza Heydari
hamid reza Heydari

Reputation: 62

you can use method include like this:

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

this method return true or false

Upvotes: 2

Chris
Chris

Reputation: 59551

I don't think your array really is options =['value1' : 'value1' , 'value2' : 'value2' 'value3' : 'value3' ] because this cannot compile. You should be getting an error:

Uncaught SyntaxError: Unexpected token :

What I think you want to achieve here is an object? If so, here is how to do that:

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

To then find if the value is present in the object, just do:

options.hasOwnProperty(value1)

Upvotes: 2

CodeZombie
CodeZombie

Reputation: 2087

The data input you are using is neither object nor array.This below code might help you.

For array,

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

    console.log(data); 

If the data input is array of objects,then

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

Upvotes: 2

Patryk Rudnicki
Patryk Rudnicki

Reputation: 765

If you have array:

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

you can use method indexOf as you said:

array.indexOf("a");

And this method indexOf returns -1 when the value is missing in array.

So your array should looks like

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

Upvotes: 0

Related Questions