I have an objects object. Represents each programming language and its respective color (source: github ):
colors = {
'1C Enterprise': {
'color': '#814CCC',
'url': 'https://github.com/trending?l=1C-Enterprise'
},
'ABAP': {
'color': '#E8274B',
'url': 'https://github.com/trending?l=ABAP'
},
'ActionScript': {
'color': '#882B0F',
'url': 'https://github.com/trending?l=ActionScript'
},
'Ada': {
'color': '#02f88c',
'url': 'https://github.com/trending?l=Ada'
}
//...
}
How would a function be made with Javascript which, receiving the name of a language, would return its color. For example devolverColor('Ada')
return#02f88c
I would put:
You can make a function and pass the language as a parameter, but like the other example that they just sent you, you have to make sure that the language is well written.
The function would be very simple:
BUT it is not safe.
Let's see:
All good here
NOT EVERYTHING GOOD HERE
The problem is that this function allows us to pass anything to it. Who is going to control that? Suppose we try to find
Ada5
:Better here
So, it is convenient to write a safe function, which returns at least
null
if it does not find the property that is being passed:another bonus
Note that an interesting re-game could be made for the
url
: it would be to combine the received parameter with the variableurlGit
... I have not dared to do it because the values are not normalized in the case of the first option. I put this note to open that possibility, looking to simplify the code, making it less repetitive.Try accessing the properties of an object using index access
objeto[nombrePropiedad]
.Example:
Just make sure you send him the property name correctly.
You can also define a function that returns the color directly if you need it: