Skip to content

Instantly share code, notes, and snippets.

@edgvi10
Last active March 7, 2021 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edgvi10/864cfb95e746c5c3a9757aa77ad9493f to your computer and use it in GitHub Desktop.
Save edgvi10/864cfb95e746c5c3a9757aa77ad9493f to your computer and use it in GitHub Desktop.
Javascript Object Search
Array.prototype.search = function (keyword, options) {
const results = [];
if (options === undefined) options = {};
this.map(item => {
if (typeof item === "object") {
var keys = Object.keys(item);
if ("fields" in options)
keys = options["fields"];
let found = false;
keys.map(key => {
var field = item[key].toString();
if ("ignoreCase" in options) {
if (field.search(keyword) !== -1)
found = true;
} else {
if (field.toLowerCase().search(keyword.toLowerCase()) !== -1)
found = true;
}
});
if (found) results.push(item);
} else {
if (item.toString().search(keyword) !== -1) results.push(item);
}
});
return results;
}, false;
// Examples
const products = [];
products.push({ "label": "Beef", "cat": "Food" });
products.push({ "label": "Tomato", "cat": "Food" });
products.push({ "label": "Football", "cat": "Toys" });
products.push({ "label": "Bandaid", "cat": "First-aid" });
products.search("Foo") // [{ "label": "Beef", "cat": "Food" }, { "label": "Tomato", "cat": "Food" }, { "label": "Football", "cat": "Toys" }]
products.search("Foo", { fields: ["label"] }) // [{ "label": "Football", "cat": "Toys" }]
products.search("Ba", { ignoreCase: false, fields: ["label"] }) // [{ "label": "Bandaid", "cat": "First-aid" }]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment