In javascript, given value, find the name from Object literal

I am new JavaScript and trying to find an easier way to find the name given the value from the object literal.

eg.

var cars ={ Toyata: ['Camry','Prius','Highlander'], Honda: ['Accord', 'Civic', 'Pilot'], Nissan: ['Altima', 'Sentra', 'Quest']}; 

Given the β€œConsent,” I want to get a Honda from the Cars facility.

+2
source share
3 answers

You will need to execute a loop, for example:

 function getManufacturer(carName) { for(var key in cars) { if(cars.hasOwnProperty(key)) { for(var i=0; i<cars[key].length; i++) { if(cars[key][i] == carName) return key; } } } return "Not found"; } 

Here you can check it , just like a working cross browser, it ignores the existence of .indexOf() , since IE does not have it ... this version will look like this

 function getManufacturer(carName) { for(var key in cars) { if(cars.hasOwnProperty(key) && cars[key].indexOf(carName) != -1) { return key; } } return "Not found"; } 
+3
source

If you intend to do this once, use a function similar to the one that Bobby gave. If you are going to do this several times, I would suggest creating a reverse mapping of cars with manufacturers:

 var manufacturers = {}; // create a map of car models to manufacturers: for (var manf in cars) { /* see note below */ for (var i=0; i<cars[manf].length; i++) { manufacturers[cars[manf][i]] = manf; } } // Now referencing the manufacturers is // a very fast hash table lookup away: var model = 'Accord'; alert(manufacturers[model]); 

note for those who have spiteful downward fingers. For objects that do not inherit anything as specified in the OP, the hasOwnProperty check is not needed here. For objects that inherit this depends on the programmer. If you want consistency through inheritance, then the hasOwnProperty check is exactly what you DO NOT want. If you do not care about inheritance, use the hasOwnProperty check, but if so, you would not inherit in the first place, which would make the hasOwnProperty check unnecessary. In the rare case when you are forced to create an object through inheritance, but do not want to check the parent attributes, you must perform a hasOwnProperty check. Of course, if you use a library like Prototype.js, which insists on modifying the Object, then I am sorry for you because you are forced to perform a hasOwnProperty check.

+1
source

Maintain separate display models for manufacturers.

 var cars ={ Toyata: ['Camry','Prius','Highlander'], Honda: ['Accord', 'Civic', 'Pilot'], Nissan: ['Altima', 'Sentra', 'Quest']}; var models = {}; var hasOwnProperty = Object.prototype.hasOwnProperty; for (key in cars) { if (hasOwnProperty.call(cars, key)) { var i=0,l=cars[key].length,manufacturer=cars[key]; while (i<l) { if ( ! hasOwnProperty.call(models, manufacturer)) { models[manufacturer] = key; } else { // Throw an error, or change the value to an array of values } i++; } } } 
-1
source

Source: https://habr.com/ru/post/905098/


All Articles