Nick
Nick

Reputation: 1541

Filtering array of objects if specific key contains search term

I am trying to filter through an object with multiple key/value pairs by a specific key. It appears that the code I've written is searching the entire object regardless of the key...

If key name contains the search term, return the search term.

Array of Objects:

export const someArrayOfObjects = [
  { id: '1', name: 'Something' },
  { id: '2', name: 'Another' },
  { id: '3', name: 'Lets do one more' },
]

Search:

const searchResults = someArrayOfObjects.filter((o) =>
      Object.keys(o).some((k) => o[k].toString().toLowerCase().includes(searchTerm.toLowerCase()))
    );

So if I search "Something", I only want it to loop through name to search for that term...

Upvotes: 1

Views: 1465

Answers (2)

exquizzle
exquizzle

Reputation: 1

similar to iota's, you don't need to create the extra array with Object.keys. just loop/check every item inside the original array with the 'name' key. you can also try to make it more reusable like below.

const someArrayOfObjects = [
  { id: '1', name: 'Something' },
  { id: '2', name: 'Another' },
  { id: '3', name: 'Lets do one more' },
];

const search = function (anyArray, searchTerm) {
  return anyArray.filter((obj) => {
    if (obj.name === searchTerm) {
      return obj.name;
    }
    return false;
  });
};

const case1 = search(someArrayOfObjects, 'Something');
console.log(case1);

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89139

You don't need the Object.keys loop.

const someArrayOfObjects = [
  { id: '1', name: 'Something' },
  { id: '2', name: 'Another' },
  { id: '3', name: 'Lets do one more' },
];
let key = 'name';
let searchTerm = 'th';
const res = someArrayOfObjects.filter(o => 
   o[key].toLowerCase().includes(searchTerm.toLowerCase()));
console.log(res);

Upvotes: 4

Related Questions