This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 7 years ago.
I am trying to use a variable to select from an array:
This works:
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
But this does not work:
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
var myvalue = "bricks"
function Two() {
alert(myarray.myvalue);
}
How do I do this properly? Here is a fiddle to show what I am trying to accomplish: https://jsfiddle.net/chrislascelles/xhmx7hgc/2/
Use the [] notation.
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
var myvalue = "bricks" //supplied here to make example work
function Two() {
alert(myarray[myvalue]);
}
Demo
The variable is not an array, it's an object.
To access an element from object using variables you should use Bracket Notation like bellow
alert(myarray[myvalue]);
Fiddle
The only thing you are lacking is the syntax. Here is how it works:
function Two() {
alert(myarray[myvalue]);
}
In javascript, it means the same thing to write these two:
var a = {};
a.foo = "hello";
a["bar"] = "world";
a.bar; // world;
a["foo"]; // hello;
Related
This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 6 years ago.
I guess I didnt really know how to ask this question for me to find an answer.
So I have three variables that are going to make this function do what it has to
function gatherDataForGeographic(ele) {
var $this = $(ele)
var $main_title = $this.find('.options-title'),
$option = $this.find('.option');
var arr = []
var reportAreas = reportManager.getReportAreasObject();
$option.each(function () {
var $this = $(this)
var $checkbox = $this.find('.checkbox');
var type = $this.data('type'),
index = $this.data('index');
if ($checkbox.hasClass('checkbox--checked')) {
console.log(reportAreas.type)
} else {
return true;
}
})
return arr;
}
//this will return an object that I need to index
var reportAreas = reportManager.getReportAreasObject();
//this will get the a key that i need from the object
var type = $this.data('type');
//this will give me the index I need to grab
var index = $this.data('index');
So what I am trying to do is go through the object based on the type(or key) from the option selected by a user
The problem...
It is looking for reportArea.type[index] and is not recognizing it as a variable and I keep getting undefined because .type does not exist.
Is there a way for it to see that type is a variable and not a key?
You can use dynamic properties in JS using the bracket syntax, not the dot syntax:
reportAreas[type]
That will resolve to reportAreas['whateverString'] and is equivalent to reportAreas.whateverString- reportAreas.type however, is a literal check for type property.
reportArea[type][index]
JavaScript objects are just key-value pairs and the dot syntax is just syntactic sugar for the array notation.
object['a']
and
object.a
Are the same thing, basically.
This question already has answers here:
How to find JavaScript variable by its name
(7 answers)
Closed 7 years ago.
I saw a lot of answer to call a method from a given object using a string, but no one to get the object itself.
I would like something like that
var a
var b
var c
function getObject(objectAsString)
{
return getMyObject(objectAsString);
}
then if I write
var obj=getObject("a")
my result is obj=a
Is there a function "getMyObject"?
Thanks
See following code
<script>
//in one script
var GlobalvarName = 500;
alert(window["GlobalvarName"]); //alert is : 500
</script>
you could do:
var hello = 'Hello World';
this['hello'];
I wouldn't make those variables so global though. here's why
Instead put them inside an object like:
var obj = {
a: 'Hello',
b: 'World'
}
console.log(obj['a'], obj['b']);
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I know that you can evaluate the value of a property inside of a JS object, like the following:
let object = {
value: 5+5
};
I am wondering if there is any possible way to evaluate the name of an attribute with JS, i.e. achieve the following:
let object;
object[5+5].value = "ten";
As something like:
let object = {
5+5: "ten"
};
Yes in ES2015, no in ES5, but first let's clear one thing up: that's JavaScript, not JSON.
In ES2015 (formerly known as ES6):
var something = "foo";
var object = {
[something]: "bar";
};
alert(object.foo); // "bar"
Inside the [ ] can be any expression you like. The value returned is coerced to a string. That means you can have hours of fun with stuff like
var counter = function() {
var counter = 1;
return function() {
return counter++;
};
};
var object = {
["property" + counter()]: "first property",
["property" + counter()]: "second property"
};
alert(object.property2); // "second property"
JSON is a serialization format inspired by JavaScript object initializer syntax. There is definitely no way to do anything like that in JSON.
Sure. Try this:
'use strict';
let object = {
[5+5]: "ten"
};
console.log(object); // Object {10: "ten"}
This question already has answers here:
Get name of object or class
(8 answers)
Closed 8 years ago.
I would like to know how I can get the name of my custom object in javascript?
var calendarDay = function (date) {
//someCode
}
var test = new calendarDay(new Date());
console.log(typeof test); //Object
However, if I do this in Chrome:
console.log(test);
Chrome shows the exact name of my customObject. Can I do this in javascript?
You're looking for test.constructor.name. You should note however that this will only work with named functions, not function expressions wherein a variable is assigned an anonymous function.
// named function, not function expression
function calendarDay (date) {
//someCode
}
var test = new calendarDay(new Date());
console.log(test.constructor.name); //"calendarDay"
EDIT:
Big surprise, as #Bergi pointed out, it's not fully supported by IE. Check out the full compatibility table on the MDN Docs
Not sure if this could help you.
give a name for your custom function obj.
var calendarDay = function (date) {
this.name = 'calendarDay';
}
var test = new calendarDay(new Date());
console.log(test.name);
This question already has answers here:
dynamic keys for object literals in Javascript [duplicate]
(8 answers)
How do I interpolate a variable as a key in a JavaScript object?
(6 answers)
Closed 9 years ago.
In JavaScript, is there a shorter way to create object from a variable then below.
var d = 'something';
function map(d){
var obj = {};
obj[d] = d;
return obj;
}
well, the shortest looks like, but it is wrong as key is literal d than its value.
function wrong(d){
return {d:d}
}
I don't mind the first version, but wonder any succinct way.
thanks.
I recommend instantiating an anonymous function.
function map(d) {
return new function () {
this[d] = d;
};
}
Using an anonymous function will allow you to keep all of your property declarations in the same place to be more organized. If you need other default keys set you can add them easily:
new function () {
this[d] = d;
this.foo = 'bar';
};
Versus with an object literal you'll have declarations in two places:
obj = {
foo: 'bar'
};
obj[d] = d;
That all said, the original code is fine as-is. It's concise, readable, and maintainable.
function map(d) {
var obj = {};
obj[d] = d;
return obj;
}