I get an array of values from an API:
values = ['Banana','Yellow','Columbia'];
I also receive a separate array of keys:
keys = ['Fruit','Color','Producer'];
I can format this info with a template literal:
function getRow(values){
return `The <b>${values[0]}</b> you are eating
is ${values[1]} and was produced in ${values[2]}`;
}
getRow(values);
// "The <b>Banana</b> you are eating is Yellow and was produced in Columbia"
This is the desired result but, for clarity, how can I combine values
and keys
in such a way that the template literal may become:
`The <b>${Fruit}</b> you are eating
is ${Color} and was produced in ${Producer}`
3
Answers
If you want to do something like this, you’ll need to merge your keys and values into an object, then use that object in your function.
Since your array of keys seems to be dynamic, hard-coding these into variables seems counter-productive. The keys are still hardcoded into your template, but that’s less of an issue: nonexisting keys will just show
undefined
.I deliberately changed the template a little bit, so we wouldn’t have to mess around with the creation of variables, as there’s no safe way to do so without requiring excessive input validation, in order to prevent the code from breaking by accessing undefined variables or overriding existing values.
You can use the spread operator to map values and then use them in the template literal:
EDIT
The use of
eval
may be unsafe in many circumstances, particularly when theString
that we pass to it contains unsanitised and potentially dangerous content. The approach above solves your issue, but you will need to be absolutely sure that bothkeys
andvalues
are entirely harmless. Also, since this is a very dynamic solution, it is up to you to make sure you use it correctly. If you have a different number of items inkeys
andvalues
, for example, then this will not work.That was an interesting question for me and I decided to see what can I do …
Here is what you can do to get what you need but note that this only works if your values array and your keys array are in order with each other.
So the solution is that you can build an object inside that function (or out of it if needed) and then use the forEach loop to fill in the object, in here I will create the object outside of the function you need:
So what have I done here basically is that I have first created an empty object, the object that I want to fill it with the forEach loop.
After creating the empty object, I created a loop for the values array and starting looping over it and in each iteration, this process goes on:
First with
obj[keys[index]]
we are setting the key for that property and then by= val
we link that value in that iteration to the key and when this loop finishes you will have this object:And then if you want to get a value from an object based on its key, you have to use dot notation like
obj.Fruit
or bracket notation likeobj['Fruit]
I hope this helped to fix your problem