How to simulate this PHP function in jQuery?

2

The below function in PHP will return me an array where the searched word fit, how can I do the same with jQuery?

$meuArrayMultidimensional = array(array("campo" => "teste"), array("campo" => "valor qualquer"), array("campo" => "teste"));
$search = "uma palavra qualquer";
$retorno = array_keys(
    array_filter(
    $meuArrayMultidimensional,
        function ($value) use ($search) {
            return (stripos($value['colunaDoArray'], $search) !== false);
        }
    )
);
    
asked by anonymous 24.11.2016 / 23:29

1 answer

1

If the purpose is to filter for later fetching the field, you can use the array.filter() " - if it is to take index , you can use array.forEach()

The equivalent of stripos is "string".indexOf() and you can not hit false because it returns 0 if the index found is at position 0 of the string. you can also use search - if you need to use RegEx (pex "hello world".search(/\sworld/i) )

To iterate over an object, you can do iterating through your keys with Object.keys() :

var objectoMultidimensional = {'0':{campo: 'teste'},'1':{campo: 'valor qualquer'}, '2':{campo: 'teste'}}
var result3 = [], objecto;
Object.keys(objectoMultidimensional).forEach(function(key, index) {
   objecto = objectoMultidimensional[key]; 
   if (objecto.campo.indexOf(search) > -1) {
       result3.push(objecto)
   }
});

console.log(result3)

You can still use Object.values allied to array.filter if the browser supports it (or if you're using a shim):

var result4 = Object.values(objectoMultidimensional).filter(function(objecto) { 
    return objecto.campo.indexOf(search) > -1 
})

console.log(result4)

How do you repair, Object.values() returns an array with the values inside the object provided, instead that Object.keys() only returns the keys of the same.

To do the same with the search() I mentioned above:

var search = 'TESTE';
var regExp = new RegExp(search, 'i');
var resultado = ['olá', 'mundo', 'teste'].filter(function(text) { return text.search(regExp) > -1 });
console.log(resultado);
    
25.11.2016 / 04:09