JS search in object values
Something like this:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
];
var results = [];
var toSearch = "lo";
for(var i=0; i<objects.length; i++) {
for(key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
results.push(objects[i]);
}
}
}
The results array will contain all matched objects.
If you search for 'lo', the result will be like:
[{ foo="lorem", bar="ipsum"}, { foo="dolor", bar="amet"}]
NEW VERSION - Added trim code, code to ensure no duplicates in result set.
function trimString(s) {
var l=0, r=s.length -1;
while(l < s.length && s[l] == ' ') l++;
while(r > l && s[r] == ' ') r-=1;
return s.substring(l, r+1);
}
function compareObjects(o1, o2) {
var k = '';
for(k in o1) if(o1[k] != o2[k]) return false;
for(k in o2) if(o1[k] != o2[k]) return false;
return true;
}
function itemExists(haystack, needle) {
for(var i=0; i<haystack.length; i++) if(compareObjects(haystack[i], needle)) return true;
return false;
}
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor blor",
"bar" : "amet blo"
}
];
function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('lo '));
Find a value in an array of objects in Javascript
You can loop over the array and test for that property:
function search(nameKey, myArray){
for (let i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
const array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
const resultObject = search("string 1", array);
console.log(resultObject)
How to get a key in a JavaScript object by its value?
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
ES6, no prototype mutations or external libraries.
Example,
function getKeyByValue(object, value) { return Object.keys(object).find(key => object[key] === value);}
const map = {"first" : "1", "second" : "2"};console.log(getKeyByValue(map,"2"));
Javascript-searching for a string in the properties of an array of objects
Assuming you want to find the substring in the property value, you can use the following code:
const arr = [ {a:'abc', b:'efg', c:'hij'}, {a:'abc', b:'efg', c:'hij'}, {a:'123', b:'456', c:'789'},];
const search = 'a';
const res = arr.filter(obj => Object.values(obj).some(val => val.includes(search)));
console.log(res);
JS search for both object keys and values
You could use a mix of Object.entries
, Array.filter
& Array.some
to achieve what your after.
Below is an example.
var jsobject = {
"/football/": {
"title": "(:title)",
"description": "Shop (:title) online ",
"index": "true",
"follow": "true",
"CANONICAL": "/football/"
},
"/league/": {
"title": "(:title)",
"description": "Shop (:title) online",
"index": "true",
"follow": "true",
"CANONICAL": "/bayern-munich/p/replica"
},
"/club/fulham/": {
"title": "(:title)",
"description": "Shop (:title) online for football league",
"index": "true",
"follow": "true",
"CANONICAL": "/fulham/"
},
"/championship/": {
"title": "(:title)",
"description": "Shop (:title) online for championship",
"index": "true",
"follow": "true",
"CANONICAL": "/socks/"
}
};
function filterAll(obj, search) {
return Object.fromEntries(
Object.entries(obj).filter(([k,v]) =>
k.toLowerCase().includes(search)
|| Object.entries(v).some(([k,v]) =>
typeof v === 'string'
&& v.toLowerCase().includes(search)
)));
}
console.log(filterAll(jsobject, 'football'));
Search/Filter JavaScript Object Array
Some issues:
The duplicates get added because after adding an object, you keep looking for more matches in the same object. So if there is any other key that matches, the same object will be added twice
When the search includes a space, your description says you want to treat that as a separator for multiple search terms, but your code never splits the search argument like that.
There is no
return
statement in your functionThe key variable is not declared with
var
,let
orconst
I would suggest solving this with filter
: this guarantees that you won't get duplicates. Then require that all search terms have a match: for this you can use split
and every
. Then require that there is at least one key that matches a search term: for this you can use some
:
Don't name your search function with PascalCase, but with camelCase (so search
instead of Search
). The common practice is that PascalCase is reserved for constructor/class names.
const search = toSearch => {
let terms = toSearch.split(" ");
return objects.filter(object =>
terms.every(term =>
Object.values(object).some(value =>
value.includes(term)
)
)
);
}
Search in Array of objects on multiple values
const data = [{
caseNumber: 123,
patientName: 'Adam',
technician: 'Jasicca',
reader: 'Potter',
},
{
caseNumber: 456,
patientName: 'John Doe',
technician: 'Kevin',
reader: 'Harry',
},
{
caseNumber: 789,
patientName: 'Ram',
technician: 'Bob',
reader: 'Jade Boe',
},
];
const input = document.querySelector('input');
const log = document.getElementById('log');
function searchArray(e) {
let filtered = [];
const input = e.target.value.toLowerCase();
if (input) {
filtered = data.filter((el) => {
return Object.values(el).some((val) =>
String(val).toLowerCase().includes(input)
);
});
log.textContent = JSON.stringify(filtered);
}
}
<input placeholder="Enter some text" name="name" onkeyup="searchArray(event)" />
<p id="log"></p>
Search JS Object for Value
There isn't really a better (more efficient) way without introducing another data structure. The answer really depends on your usage but you could do a few different things:
Create separate 'indexes' using hashes. These structures would map keys to the items or the index in the source array. JavaScript objects/hashes support key based lookup and should be efficient.
userinfo[x].username = "foo";
// Index the objects
usersByName = {};
usersByName["foo"] = userinfo[x];
// -- OR -- index the array indices
var usersByName["foo"] = x;
// Test for key
"foo" in usersByName; // trueYou'll have to put in a little more work to maintain consistency between the index and the source array. It's probably best to wrap both in another object to manage the contents of both. This approach is nice if there are multiple fields that you want to look objects up by.
If you don't care about the order of the collection you could just change the whole thing to a hash and index by username
var userinfo = {};
userinfo["foo"] = {username: "foo", firstName: "Foo", lastName: "Bar"};
One thing to think about, though, is if the efficiency gains are going to outweigh the increased code complexity of maintaining indexes. If you aren't doing a lot of searches and you don't have tons of items in the userinfo collection it may make more sense to just write a general use searching function or use a library like what Philip Schweiger was mentioning.
function findObjectByAttribute (items, attribute, value) {
for (var i = 0; i < items.length; i++) {
if (items[i][attribute] === value) {
return items[i];
}
}
return null;
}
var userinfo = [];
userinfo[0] = {username: "foo"};
console.log(findObjectByAttribute(userinfo, "username", "foo"));
Related Topics
How to Make API Call with Hooks in React
Fastest Way to Check a String Contain Another Substring in JavaScript
How to Display Binary Data as Image in React
Getting All Selected Checkboxes in an Array
Sum of Array Object Property Values in New Array of Objects in JavaScript
What Are the Current Cookie Limits in Modern Browsers
How to Access Component Methods from "Outside" in Reactjs
Is There a Sleep Function in JavaScript
How to Search JSON Tree with Jquery
Referenceerror: Fetch Is Not Defined
Jasmine: Async Callback Was Not Invoked Within Timeout Specified by Jasmine.Default_Timeout_Interval
Using Number as "Index" (JSON)
<Iframe> JavaScript Access Parent Dom Across Domains
Typescript Type 'String' Is Not Assignable to Type
JavaScript Can't Access Private Properties
Node.Js: Read a Text File into an Array. (Each Line an Item in the Array.)
Displaying a Number in Indian Format Using JavaScript
How to Remove Only the Parent Element and Not Its Child Elements in JavaScript