search for specific values in structure in javascript

You can use Array.prototype.filter method to search for specific values in an array of objects. Here is an example:

Suppose we have an array of objects, cars:

index.tsx
const cars = [
  { make: 'Honda', model: 'Civic', year: 2010 },
  { make: 'Toyota', model: 'Corolla', year: 2015 },
  { make: 'Nissan', model: 'Maxima', year: 2018 },
  { make: 'Honda', model: 'Accord', year: 2020 },
];
220 chars
7 lines

We can use filter method to search for cars with 'Honda' make:

index.tsx
const hondaCars = cars.filter((car) => car.make === 'Honda');
62 chars
2 lines

hondaCars will be an array with two cars objects with 'Honda' make:

index.tsx
[
  { make: 'Honda', model: 'Civic', year: 2010 },
  { make: 'Honda', model: 'Accord', year: 2020 },
]
103 chars
5 lines

You can also search for values in specific keys of an object using Object.keys method and Array.prototype.includes. Here is an example:

index.tsx
const car = {
  make: 'Toyota',
  model: 'Corolla',
  year: 2015
};

const searchValue = 'Corolla';

const hasSearchValue = Object.keys(car).includes(searchValue);
console.log(hasSearchValue); // true
201 chars
11 lines

In the above example, Object.keys(car) will return an array ['make', 'model', 'year'], and hasSearchValue will evaluate to true because 'Corolla' is in the array.

related categories

gistlibby LogSnag