Last active
August 12, 2021 19:47
-
-
Save edgvi10/b7a836f62a59b530fcc1d3a8826e09cd to your computer and use it in GitHub Desktop.
Busca por campos em Array e Object 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) => { | |
if (options === undefined) options = {}; | |
if (typeof list === "object") { | |
const results = {}; | |
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 ("caseSensitive" in options) { | |
if (field.search(keyword) !== -1) found = true; | |
} else { | |
if (field.toLowerCase().search(keyword.toString().toLowerCase()) !== -1) found = true; | |
} | |
} | |
}); | |
if (found) results[item_index] = item; | |
} else { | |
if (item.toString().search(keyword) !== -1) results[item_index] = item; | |
} | |
}); | |
return results; | |
} else { | |
const results = []; | |
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 ("caseSensitive" 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