I describe the banal thing, data comes to the frontend, and this data needs to be specially processed depending on the type. For example, we have a list with animals, we need to draw it, and if it's a cat, add a picture with a ball. Model example:

var model= { "animals" = [{Id = 1, name ="Murzik", typeId = 1}, {Id = 2, name ="Snezok", typeId = 1}, {Id = 3, name ="Barbos", typeId = 2}], "animalTypes = [{typeId = 1, name="Cat"},{typeId = 2, name="Dog"},{typeId = 3, name="Fish"}] } 

If type hardcodes if(typeId = 1) are probably not an option. But it seems to me that without some kind of hardcode in one form or another can not do without excessive complication. What are the best practices for such simple cases in the world of modern web development?

  • one
    I would suggest to alter anymalTypes in a hash table. Then all typeIDs will become keys of their objects ( {1: {name: "Cat"}, ...} ). Thus, it will be possible to use the simplest map and assign additional. attributes - pictures, for example. - Mr. Brightside
  • @ Mr. Brightside is worth putting it in the form of an answer. - Arnial
  • @Arnial done - Mr. Brightside

2 answers 2

anymalTypes can be converted into a hash table.

Then all typeIDs will become keys of their objects and it will look something like this:

 { 1: {name: "Cat"}, 2: {name: "Dog"} } 

Thus, it will be possible to use the simplest map and assign additional. attributes - pictures, for example.

The situation will be even simpler if the resulting hash table contains links to the images:

 { 1: {name: "Cat", image: '/remoteFolder/catImage.png'}, 2: {name: "Dog", image: '/remoteFolder/dogImage.png'} } 

Then to get, for example, an image for Murzik, you can use:

 animalTypes[animal[0].typeId].image 

    If you just need to take a static value that corresponds to the type, then the hash table is suitable, and you can directly enter the values:

     var model= { "animals": [{Id:1, name:"Murzik", typeId:1}, {Id:2, name:"Snezok", typeId:1}, {Id:3, name:"Barbos", typeId:2}], "animalTypes": [{typeId:1, name:"Cat"},{typeId:2, name:"Dog"},{typeId:3, name:"Fish"}] }; var types = {}; model.animalTypes.forEach(e => { types[e.typeId] = e.name; }); model.animals.forEach( e => { e.type = types[e.typeId] }); /* JSON.stringify( model.animals ) [{"Id":1,"name":"Murzik","typeId":1,"type":"Cat"},{"Id":2,"name":"Snezok","typeId":1,"type":"Cat"},{"Id":3,"name":"Barbos","typeId":2,"type":"Dog"}] */ 

    If we are talking about actions depending on the type, then we need to wrap the action in a function or method, and call the appropriate one. For example, let's call the methods just like the type - Cat() , Dog() . Then we add to the code above:

     function Cat() { /* рисуем клубок */ } function Dog() { /* косточку */ } function Fish() { /* червячка */ } model.animals.forEach( e => { if( this[ e.type]) this[ e.type](); // вызов ф-ии, если такая есть });