1

How can i using dynamic values for evaluating expressions? For instance, consider the below example,

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);

What if a and b are dynamic names? means instead of a and b it can be anything like 'someValue' . how to do something like below? (name can be dynamic)

 var 'someValue' = 1;
 console.log(`*Fifteen is ${'someValue' + b}* and not ${2 * a + b}.`);

In a nutshell i want to evaluate an expression where the field names are dynamic. So i wont be able to define variables statically. How do i overcome this?

Victor
  • 4,171
  • 1
  • 29
  • 37
  • What do you mean by "field names"? – guest271314 Oct 03 '17 at 07:23
  • have you tried ` console.log(`*Fifteen is ${someValue} ${b}* and not ${2 * a + b}.`);` ? – archeal anie Oct 03 '17 at 07:24
  • names = 'a' , 'b' can be anything.. i cant define someValue statically – Victor Oct 03 '17 at 07:24
  • If the "names" "can be anything" how will you know what they are? How do you know when `someValue` is defined within the current scope? – guest271314 Oct 03 '17 at 07:25
  • i need to programatically find the value ..say i was able find a =10 .. but how will dynamically assign the value to expression without defining the value before the expression? – Victor Oct 03 '17 at 07:29
  • _"i need to programatically find the value"_ Can you create a stacksnippets to demonstrate? See https://stackoverflow.com/help/mcve – guest271314 Oct 03 '17 at 07:30

4 Answers4

3

You can use bracket notation and this keyword which is a reference to the window object.

window.name="Vicky";
window.test="test";
const message = (p0, p1) => `Hello, ${p0}. This is a ${p1}`;
console.log(message(window['name'],window['test']));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

Maybe eval will suits your needs. But be careful with this function.

function test() {
  var a = 'Hello World',
      b = 1,
      c = 2,
      myVarRefA = 'a',
      myVarRefB = 'b',
      myVarRefC = 'c';
  
  console.log(`${eval(myVarRefA)} ${eval(myVarRefB + ' + ' + myVarRefC)}`);
}

test();
Serge K.
  • 5,303
  • 1
  • 20
  • 27
0

You can use a temporary Object with variables as its attributes

let temp = Object.create(null);
temp["someVar"] =3;
temp["anotherVar"]=2;
console.log(temp["someVar"] + temp["anotherVar"]);

But you can also use the more elegant

let temp = Object.create(null);
temp.someVar =3;
temp.anotherVar=2;
console.log(temp.someVar+ temp.anotherVar);

Do be careful about your "this" bindings

0

If your field names are completely custom, you can get use of Object.keys(..). This method will let you loop through the properties in an object.

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Example (Just to show usage)

    const customObject = { name: 'Foo', age: 23, city: 'Bar City' };
    const getFormatedObject = (fieldsObject) => {
      const fields = {};
      Object.keys(fieldsObject).forEach((fieldName, index) => {
        fields[`f${index}`] = fieldsObject[fieldName];
      });
      return fields;
    }
    const formatedObject = getFormatedObject(customObject);
    for (let i = 0; i < Object.keys(formatedObject).length; i++) {
      console.log(formatedObject[`f${i}`]);
    }

If you know the number of fields on your object you can go with something like below.

const customObject = { name: 'Foo', age: 23, city: 'Bar City' };
const keys = Object.keys(customObject);
console.log(`His ${keys[0]} is ${customObject[keys[0]]} and ${keys[1]} is ${customObject[keys[1]]} and ${keys[2]} is ${customObject[keys[2]]}`);
bennygenel
  • 23,896
  • 6
  • 65
  • 78