Função de Busca por objetos ou arrays em javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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