[Javascript] How do I search for all the objects in my database that have the same property values? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

[Javascript] How do I search for all the objects in my database that have the same property values?

For example, I'd have something like var car1 = { make:'Ford'; model: 'F150'; color: 'blue'; } var car2 = { make: 'Ford'; model: 'Fiesta'; color: 'yellow'; } and I want to be able to type into a textbox "Ford" and have both pop up or type in "yellow" and have only car2 show up. How do I accomplish this?

17th May 2020, 7:41 PM
Michael
5 Answers
+ 6
Michael Greetings :)) First of all fetch all your objects from the database, then push them in an array. Let's call it 'objects'. Now, iterate through it : const search = 'Ford'; objects.forEach(data => { if (data.make === search) { console.log(data.color); // blue, yellow } }); Now, if you want to search by color, change data.make to data.color and the search to 'yellow'. :))
17th May 2020, 7:48 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 2
You have a syntax error. You used semicolons instead of commas to seperate object properties. If you fix that. Then with this additional code you can search your objects const carsArr = [car1, car2]; function searchCars(search_str, cars=carsArr){ return [...cars].filter(car => search_str == car.make); } const results = searchCars("Ford"); results.forEach(car=>console.log(Object.values(car))); To search for colors instead, just change car.make to car.color in the return statement
17th May 2020, 10:32 PM
Ore
Ore - avatar
+ 1
its actually mostly done with SQL, a database management language where you store excel tables of information and search in good ways. like searching models with ford like this for example SELECT somedatatablewithinformatiom FROM cars WHERE model="Ford"
17th May 2020, 7:47 PM
Korijn Jagersma
Korijn Jagersma - avatar
+ 1
oh haha thats it, a great solution!
17th May 2020, 7:49 PM
Korijn Jagersma
Korijn Jagersma - avatar
0
I dont know how to do it in JS quite sadly...
17th May 2020, 7:48 PM
Korijn Jagersma
Korijn Jagersma - avatar