JSON Search
/
Esta clase permite buscar una cadena de texto en un JSON de forma genérica (en todos los campos especificados).
# Métodos
# Método query
Realiza una consulta en la fuente (
source) en los campossearchBy(si se ha establecido).
Por defecto busca en todos los campos del JSON.
- Returns: JSON Object / false
# Argumentos
# source:
- Requerido
- type: JSON Object
- Explicación: Recibe la fuente de datos para el buscador.
# searchBy
- (Opcional)
- type: Array (String)
- Explicación:
# targetEl
- (Opcional)
- type: DOM Element
- Explicación: Elemento HTML en el que se renderizarán los resultados. Si no se especifica un
targetEl, la funciónrenderdevolerá un objeto JSON con los resultados de la búsqueda.
# template
- (Opcional) / Requerido si se utiliza
targetEl- type: Function
- arguments:
- fields: JSON Object --> Recibe en un objeto JSON los campos definidos en el
sourcede los elementos devueltos por los resultados de la búsqueda.
- fields: JSON Object --> Recibe en un objeto JSON los campos definidos en el
- Explicación: Función de renderizado en el que se indica cómo se deben mostrar los campos dentro del elemento target
targetEl.
# Funcionamiento
Se realiza una instancia de la clase JSONQuerySearch:
// Fuente JSON
var books = [
{
"title": "Cracking the coding interview",
"subtitle":"189 programming questions and solutions",
"author":"Gayle Laakmann McDowell",
"category":"Programming",
"publisher":"CareerCup, LLC"
},
{
"title": "No friend but the mountains",
"subtitle":"Writing from manu prison",
"author":"Behrouz Boochani",
"category":"Literature",
"publisher":"Pan Macmillan Australia"
},
...
];
// Selector del elemento HTML (Opcional)
var target = document.querySelector('#target');
// Instancia de la clase
var search = new JSONQuerySearch({
source:books,
targetEl: target,
template: function(fields){
var {title, subtitle, author, publisher, category} = fields;
return `<div>
<h2>${title}</h2>
<i>${subtitle}</i>
<p><strong>${category}</strong></p>
<p>${author} - ${publisher}</p>
</div>`;
}
});
// Uso de la clase
search.query('programming');
# Source
class JSONQuerySearch {
constructor(args){
this.props = {
source: [],
fields: null,
searchBy: null,
targetEl: null,
template: null,
...args
}
this.query = this.query.bind(this);
this.render = this.render.bind(this);
}
isElement(obj) {
try {return obj instanceof HTMLElement;}
catch(e){
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object");
}
}
render(data) {
var {template} = this.props;
if(this.isElement(this.props.targetEl) && template){
this.props.targetEl.innerHTML = data.map(function(element){
return template({... element});
}).join('');
return true;
}
else return data;
}
query(searchTerm) {
var {searchBy, source} = this.props;
searchTerm = searchTerm ? searchTerm : '';
var tokens = searchTerm.toString()
.toLowerCase().split(' ')
.filter(function(token){
return token.trim() !== '';
});
var results = [];
var filteredList = source
if(tokens.length) {
var searchTermRegex = new RegExp(tokens.join('|'), 'gim');
filteredList = filteredList.filter(function(element){
var valuesString = '';
for(var key in element) {
if( (!searchBy || (searchBy && searchBy.indexOf(key) > -1)) && element.hasOwnProperty(key) && element[key] !== '') {
valuesString += element[key].toString().toLowerCase().trim() + ' ';
}
}
return valuesString.match(searchTermRegex);
});
}
return this.render(filteredList);
}
};

