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?
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']));
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
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]]}`);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.