Is it possible to search in javascript object with something like LIKE operator by string?

Viewed 1715

I have an object, and I would like to search in it by a string. The data in object contains that string I want to update that object so there will be just data that contains the string in the results.

I tried this code:

let obj = {320936614713847: "Nibaru", 612610972204514: "Slevníme", 633965056629062: "Eye of wisdom"}

let matches = obj.filter(s => s.includes(document.getElementById('pageSearchBox').value));

console.log(matches);
4 Answers

.filter is not a method which is part of which is part of an object. Thus obj.filter isn't going to work. However, you can instead convert your object to an array of values, which will then allow you to use .filter out any value which don't match your search query. Then you can rebuild this filtered key-value array into an object using .reduce().

See example below:

let obj = {320936614713847: "Nibaru", 612610972204514: "Slevníme", 633965056629062: "Eye of wisdom"}
let searchStr = "Nib";
let matches = Object.entries(obj).filter(([_, v]) => v.includes(searchStr))
                    .reduce((acc, [k, v]) => ({...acc, [k]: v}), {})
console.log(matches);

You can not filter an object, you can only filter a list.

Knowing that, you can do something like this:

let obj = {
    320936614713847: "Nibaru",
    612610972204514: "Slevníme",
    633965056629062: "Eye of wisdom"
}

let matches = Object
    .keys(obj)
    .filter(s =>
        obj[s] === document.getElementById('pageSearchBox').value
    );

console.log(matches);

If you wanna filter by the key:

let obj = {
    320936614713847: "Nibaru",
    612610972204514: "Slevníme",
    633965056629062: "Eye of wisdom"
}

let matches = Object
    .values(obj)
    .filter(s =>
        s === document.getElementById('pageSearchBox').value
    );

console.log(matches);

Use regex for an operator similar to LIKE in SQL.

You can check the snippet for an example. This will search for anything in the object that matches the LIKE clause '%iba%'.

let obj = {320936614713847: "Nibaru", 612610972204514: "Slevníme", 633965056629062: "Eye of wisdom"}

let matches = []

// Run thorugh object
Object.keys(obj).forEach(kv => {
  if (/.*iba.*/.test(obj[kv])) { // ... LIKE '%iba%'
     matches.push(obj[kv]);
  }
});


console.log(matches);

This would be like the SQL statement:

SELECT val FROM obj WHERE val LIKE '%iba%';

Use fromEntries:

 

let obj = {320936614713847: "Nibaru", 612610972204514: "Slevníme", 633965056629062: "Eye of wisdom"}

let matches = Object.fromEntries(Object.entries(obj).filter(([, v]) => v.includes("Nib")));

console.log(matches);

Better supported version with reduce:

 

let obj = {320936614713847: "Nibaru", 612610972204514: "Slevníme", 633965056629062: "Eye of wisdom"}

let matches = Object.entries(obj).filter(([, v]) => v.includes("Nib")).reduce((a, [k, v]) => (a[k] = v, a), {});

console.log(matches);

Related