JavaScript Use Variable as Object Name

Javascript use variable as object name

Global:

myObject = { value: 0 };
anObjectName = "myObject";
this[anObjectName].value++;

console.log(this[anObjectName]);

Global: v2

var anObjectName = "myObject";
this[anObjectName] = "myvalue"

console.log(myObject)

Local: v1

(function() {
var scope = this;

if (scope != arguments.callee) {
arguments.callee.call(arguments.callee);
return false;
}

scope.myObject = { value: 0 };
scope.anObjectName = "myObject";
scope[scope.anObjectName].value++;

console.log(scope.myObject.value);
})();

Local: v2

(function() {  
var scope = this;

scope.myObject = { value: 0 };
scope.anObjectName = "myObject";
scope[scope.anObjectName].value++;

console.log(scope.myObject.value);
}).call({});

Define object field name based on variable value in javascript

The es6 version of JavaScript allows you to handle this issue, we can use variables while creating the object to dynamically set the property like so:

const field = "name";

const js = {[field] : "rafael"};

console.log(js);

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};

obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2021:

Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.

const yourKeyVariable = "happyCount";
const someValueArray= [...];

const obj = {
[yourKeyVariable]: someValueArray,
}

Can you use a variable name to reference an Object without using eval()

The answer is that you can't.

In JS, there's no way to access or create variables dynamically, unless you eval (or the very similar Function constructor).

Although the variables created in the global scope with var will become properties of the global object and you can access them on it, that's also not recommended (due to the problems arisig with var, using reserved names, etc.), and works only in the global scope (which is even worse to mess with).

The best thing you can do is to place these variables into an object instead, and that way you can access them dynamically. JS variables aren't good for that.

reference object name with variable - javascript

dayRange as you have it defined is simply an array of strings and has nothing to do with the objects you defined for representing the days of the week.

You need to change the definition of dayRange to

dayRange = [sunday, monday, tuesday, wednesday, thursday, friday, saturday];

Notice the missing "s!

Select a variable/object by it's name from many available with Javascript

JavaScript won't give you a list of declared variables and their names, so what you're trying to do won't work with plain variables unless you use eval like in Majed's answer, but I don't recommend that—using eval is generally discouraged because depending on your code it can open you up to security vulnerabilities.

What you could do instead is store JohnA and GeorgeA as properties on an object like so:

let names = {
JohnA: { countries: ... },
GeorgeA: { countries: ... }
}

and then you can programmatically access those properties:

let name = 'John';
names[name + 'A'].countries // ...

Getting the object variable name in JavaScript

This is not possible in JavaScript. A variable is just a reference to an object, and the same object can be referenced by multiple variables. There is no way to tell which variable was used to gain access to your object. However, if you pass a name to your constructor function you could return that instead:

// Define my objectfunction TestObject (name) {    return {        getObjectName: function() {            return name        }    };}
// create instancevar a1 = TestObject('a1')var a2 = TestObject('a2')
console.log(a1.getObjectName()) //=> 'a1'
console.log(a2.getObjectName()) //=> 'a2'

create object using variables for property name

If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:

var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"

If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):

Create the object first, and then add the property using square bracket notation.

var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"

If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.

Using a variable as object name in React

const DrawSymbol = (props) => {
const [state, setState] = useState("");

useEffect(() => {
if(props.type) {
// `symbols` is a array of object. you need to find one object from that array
const g = symbols.find((obj) => obj.type === props.type);
setState(g?.text);
}
}, [props]);

return <div>{state}<div>
};

Try this out.



Related Topics



Leave a reply



Submit