Search Array with case-insensitive javascript variable

Asked

Viewed 139 times

2

I need to search an array with values of the type:

equipamentos = [{marca: 'Nomedamarca1', modelo: 'Modelo1'},
                {marca: 'Nomedamarca2', modelo: 'Modelo2'},
                {marca: 'AlgumNomeComCase', modelo: 'Modelo3'},
                {marca: 'OutroNomeComCase', modelo: 'Modelo4'}]

however in my input, I want to accept values in low-case, example:

When the user enters "name", the search should return: "[Nameam1, Nameam2,Somemencomcase,Othernamecomcase]"

When the user type "someone", the search should return: "[Somesomeonecomcase]"

I am using the function filter and match, but it is not case-insensitive.

ShowDShowDropModelrep(value) {

const marca = this.modelsfull.filter( obj => obj[ 'marca' ].match( value ) );
const modelo = this.modelsfull.filter( obj => obj[ 'modelo' ].match( value ) );
Object.keys(marca).forEach(function(key) { modelo[key] = marca[key]; });
this.marcamodelo = modelo; }

Reading the documentation of the match function (mozzarella doc, W3school) I tried unsuccessfully the following:

value = '/' + value + '/gi';

One of the possible solutions would be to apply . toLowerCase() to all array positions, but I need to keep the original data with the original cases.

  • 1

    What’s wrong with using toLowerCase()? It will only change the original value if you assign it!

  • The question I need this function acting on the array, not the variable passing as parameter.. But in the case you say: obj.toLowerCase() => obj[ 'tag' ].match( value ) ?

  • 1

    It worked like this: const model = this.modelsfull.filter( obj => obj[ 'model'].toLowerCase().match( value ) ); Thanks @Wallacemaxters.

  • put the solution as an answer.

1 answer

1


On top of Wallace’s comment, I managed to solve my problem in this way:

ShowDShowDropModelrep(value) {
   const marca = this.modelsfull.filter( obj => obj[ 'marca' ].toLowerCase().match( value ) );
   const modelo = this.modelsfull.filter( obj => obj[ 'modelo' ].toLowerCase().match( value ) );
   Object.keys(marca).forEach(function(key) { modelo[key] = marca[key]; });
   this.marcamodelo = modelo;}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.