skip to Main Content

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


  1. 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.

    const values = ['Banana','Yellow','Columbia'];
    const keys = ['Fruit','Color','Producer'];
    
    const obj = Object.fromEntries(keys.map((key, index)=> [key, values[index]]));
    
    function getRow(obj){
      return `The <b>${obj.Fruit}</b> you are eating
      is ${obj.Color} and was produced in ${obj.Producer}`;
    }
    
    console.log(getRow(obj));

    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.

    Login or Signup to reply.
  2. You can use the spread operator to map values and then use them in the template literal:

    let values = ['Banana','Yellow','Columbia'];
    let keys = ['Fruit','Color','Producer'];
    function getRow(values){
      eval(`[${keys.join(",")}] = [...values];`);
      //[Fruit, Color, Producer] = [...values];
      return `The <b>${Fruit}</b> you are eating
      is ${Color} and was produced in ${Producer}`;
    }
    
    document.write(getRow(values));

    EDIT

    The use of eval may be unsafe in many circumstances, particularly when the String 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 both keys and values 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 in keys and values, for example, then this will not work.

    Login or Signup to reply.
  3. 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:

    values = ['Banana','Yellow','Columbia'];
    keys = ['Fruit','Color','Producer'];
    
    const obj = {};
    values.forEach((val, index) => {
      obj[keys[index]] = val;
    })
    
    function getRow() {
      `The <b>${obj.Fruit}</b> you are eating
    is ${obj.Color} and was produced in ${obj.Producer}`
    }
    

    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:

    {
      Fruit: 'Banana',
      Color: 'Yellow',
      Producer: 'Columbia',
    }
    

    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 like obj['Fruit]

    I hope this helped to fix your problem

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search