Skip to content

Instantly share code, notes, and snippets.

@edgvi10
Created Jan 17, 2022
Embed
What would you like to do?
Função de Busca por objetos ou arrays em javascript
export const search = (list, keyword, options) => {
const results = [];
if (options === undefined) options = {};
if (typeof list === "object") {
Object.keys(list).map(item_index => {
const item = list[item_index];
if (typeof item === "object") {
var keys = Object.keys(item);
if ("fields" in options)
keys = options["fields"];
let found = false;
keys.map(key => {
if (item[key] !== null) {
var field = item[key].toString();
if ("ignoreCase" in options) {
if (field.search(keyword) === 0) found = true;
} else {
if (field.toLowerCase().search(keyword.toString().toLowerCase()) === 0) found = true;
}
}
});
if (found) results.push(item);
} else {
if (item.toString().search(keyword) !== -1) results.push(item);
}
});
} else {
list.map(item => {
if (typeof item === "object") {
var keys = Object.keys(item);
if ("fields" in options)
keys = options["fields"];
let found = false;
keys.map(key => {
if (item[key] !== null) {
var field = item[key].toString();
if ("ignoreCase" in options) {
if (field.search(keyword) !== -1) found = true;
} else {
if (field.toLowerCase().search(keyword.toString().toLowerCase()) !== -1) found = true;
}
}
});
if (found) results.push(item);
} else {
if (item.toString().search(keyword) !== -1) results.push(item);
}
});
}
return results;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment