JavaScript: How to create an object having its string name [duplicate] - javascript

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 6 years ago.
I have a namespace and class declared in the client. In fact, I have a whole bunch of classes declared in several namespaces. I just need to get an instance of one of them when I get a string from the server on page load that contains the "dotted" namespace.class names.
Currently I use eval to do that but this causes a memory leak, so I'm trying to find an alternative way of instantiating a declared object by knowing only its name. Things like var obj = "myNamespace.myObjectName"(); won't work, obviously.
If I have an object name as a string variable I can use the eval() function to create an instance of that object:
window["myNamespace"] = {};
myNamespace.myObjectName = function() { /* blah */ };
var name = "myNamespace.myObjectName";
var obj = eval("new " + name + "()");
But for several reasons I don't want/cannot to use the eval. How can I create an object by its name without using the eval?

It sounds like you don't control the content of the name variable, so you're stuck with the . being part of the string.
Therefore, you can .split() the string into its name parts, and use .reduce() to traverse from the base object.
window["myNamespace"] = {};
myNamespace.myObjectName = function() {
this.foo = "bar"
};
var name = "myNamespace.myObjectName";
var obj = newObjectFromStringPath(name);
document.querySelector("pre").textContent = JSON.stringify(obj, null, 4);
function newObjectFromStringPath(path, base) {
return new (name.split(".").reduce(function(obj, name) {
return obj != null ? obj[name] : null
}, base || window))
}
<pre></pre>
The newObjectFromStringPath is coded to specifically target a function and call it as a constructor. You can easily make this work to fetch any value by simply removing the new in that function.

Related

Defining a nested object property in Javascript [duplicate]

This question already has answers here:
Javascript: how to dynamically create nested objects using object names given by an array
(25 answers)
Closed 6 years ago.
I need to send a JSON object to a server which requires that the properties
are nested. For example, the data object may be nested 2 levels deep. However, one cannot simply declare the object directly:
var foo = {};
foo.bar.bartwo = "data"; //Uncaught TypeError
I am currently attempting to bypass this by manually creating the nested object layer.
var foo = {};
foo.bar = {};
foo.bar.bartwo = "data"; //Successful
However, this can quickly get out of hand if the object requires multiple levels of nesting.
Is there a better method in Javascript or Jquery to handle this issue (which does not work by simply golfing the second code example)?
Clarification: The solution should be able to allow for direct access to nested properties, without necessitating that all of the intermediate properties also be created.
without defining nested object i.e foo.bar = {};
you can not use or assign value to it
javascript object must be defined first to use it
otherwise it will give you 'undefined' error i.e foo.bar is undefined
create a small method that does this
function nested(x, y){
nestedA="";
parts = x.split('.');
for(i=0; i<parts.length; i++) {
nestedA += parts[i];
eval(nestedA + ' = {}');
nestedA += '.';
}
eval(nestedA.slice(0,-1)+ '= "'+y+'"');
}
nested('foo.bar.bartwo', "data");

Access property within javascript object [duplicate]

This question already has answers here:
Get property of object in JavaScript
(3 answers)
Closed 6 years ago.
I am trying to access a property within an object and return it.
Note the name of the object can change, so accessing it using title_can_change.property will not work.
Take the following object:
{
"title_can_change":{
property: 1
}
}
How do I return the value of 'property'?
MORE INFO:
This object is being returned from a search which contains an array of results from several API's. This object is returned to detail the API the result has come from (the search goes through several API's).
So this would be more like:
apiData:{
"apiName":{
price: 500
}
}
"apiName" is not fixed and changes to say the name of the API. So it cannot be referenced by "apiName' in any of the code.
You could create a function to return the value of the property of whatever object you pass to it:
var getProperty = function(obj) {
return obj.property;
};
If you have an object and you want to access it's first key's value you can go with something like this (dirty example):
var myObj = {
"title_can_change"{
property: 1
}
}
myObj[Object.keys(myObj)[0]];
I home this helps.
So I think I know what you are wanting and here is a low-level solution that may prove valuable and show you some neat things about the language.
https://jsfiddle.net/s10pg3sh/1/
function CLASS(property) {
// Set the property on the class
this.property = property || null;
}
// Add a getter for that property to the prototype
CLASS.prototype.getProperty = function() {
return this['property'];
}
var obj = new CLASS(9);
alert(obj.getProperty());
What you are doing in the above is creating a "class" for your new variable. When you create your object with the new keyword as show you still get your normal JS object (everything is an object anyways), but you get the convenience of the getProperty method. This being on the prototype insures that any new CLASS variables you create will have that method. You can change the variable names and you will always have access to that property by having access to the instance (variable). This is a very common OO paradigm and is the strength of a prototypical language so while it may be over the top for your needs I figured I would add it as an answer here...
If this object is global, then you can use window['title_can_change']['property']. If it's just another property of another object (called another_one) you can access it with another_one['title_can_change']['property'].
Furthermore: You can have a variable (let's call it title_name) to ease the call:
....
var title_name = "title_can_change";
var myObj = window[title_name]['property'];
title_name = "title_has_changed";
var anotherObj = window[title_name]['property'];
.....
OR
....
var title_name = "title_can_change";
var myObj = another_one[title_name]['property'];
title_name = "title_has_changed";
var anotherObj = another_one[title_name]['property'];
.....
Kind of a guess here since the question is still somewhat unclear. I am assuming that you want to iterate over an objects properties whose names are unknown.
This might be a solution.
for (var property in object) {
if (object.hasOwnProperty(property)) {
// check objects properties for existence
// do whatever you want to do
}
}
Use for...in to iterate over the keys of the object and check if your inner object contains your property
var o = {
"title_can_change":{
property: 1
}
};
for (var k in o) {
if (o.hasOwnProperty(k) && o[k].property) {
return o[k].property;
}
}

Javascript variable declaration : what is "var myVariable = {}"?

I'm pretty new to plain old JavaScript and to JavaScript frameworks (such as Backbone.js, RequireJS, ...). As I was reading and trying to understand some JavaScript files that I got from a project at work (based on JQuery, Backbone and Require), I've encountered some variable declarations such as:
var myVariable = {}, itemList;
Could someone explain to me what the "{}" is?
PS: might be a silly question but it's definitely not that easy Googling for "{}" as keyword...
Thanks in advance.
{} is just the javascript way of defining a collection or object.
In this example, it is filled with an object literal
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
var featurelessApple = {};
It's an empty Javascript object literal (A shorthand way of creating an object)
var myVariable = {};
is similar to
var myVariable = new Object();
Both expressions will create an empty object.
myVariable is an object literal, or generic object.
For future reference you can easily see this by using the console in your browser. In Chrome
var myVariable = {}
console.log(myVariable);
This will then print out the entire object. In this
Object {}
That's an empty object literal.
Object literals consist in zero or more key/value pairs enclosed in curly braces. In your example, there are zero key/value pairs, so the object does not define any property.

What is the difference in methods to call upon a JSON object by key name? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I tried my best to think of a name of this question, I'll change it if I can get some terminology to help
Best way I can describe it is this
obj1 = {
"a":{"var":1},
"b":{"var":2},
"c":{"var":3}
}
// What's the difference between
resulta = obj1['a']['var']
// and...
resultb = obj1.a.var
So, what's the difference between using [''] and . ?
I realize you can only use . to run functions, but is that the only difference?
Is one method faster than the other? (even a little?)
The first method with square brackets is handy if you're dynamically building your object's property keys:
var myDynamicKey = "a";
var result = obj[myDynamicKey]["var"];
var result = obj["someOtherKey_" + myDynamicKey]["var"];
The second one is definitely preferred if you know what the properties are in advance.
Note you can mix and match them:
var result = obj[myDynamicKey].var;
I'd be willing to bet that accessing properties using dot notation is faster, but I have no actual data to support that.
If you use the [''] then you can pass the name of the key in as a dynamic variable... which can change at run time. If you use the .key.key method, then you have to know at build time what the keys are.
Example:
var keys = ['name','phone','email'];
var object = {"name": ,"phone": , "email"};
function updateKeys(name,phone,email){
for(var i = 0; i < keys; i++){
object[keys[i]] = arguments[i]
}
}
vs
function updateKeys(name, phone, email){
object.name = name;
object.phone = phone;
object.email = email
}
The [''] way is much more flexible and allows for more code resuse. Most libraries will use this, or some homegrown replacement of the [''] way of doing things.
There are various websites with information about this.
http://www.quirksmode.org/js/associative.html
or
http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)
or
http://www.mongodb.org/display/DOCS/Dot+Notation+(Reaching+into+Objects)
The first I would call dot notation which can be used to access Methods and Properties of an object, and the 2nd is Associative Array.

Meaning of '{ }' in javascript

What does assigning a variable to {}, mean? Is that initializing it to a function? I have code in a javascript file that says this
GLGE.Wavefront = function(uid) {
GLGE.Assets.registerAsset(this,uid);
this.multimaterials = [];
this.materials = {}; // <---
this.instances = [];
this.renderCaches = [];
this.queue = [];
};
how is that assignment different from an array? Is it a type of array?
What does assigning a variable to {}, mean?
It is an object literal (with no properties of its own).
Is that initializing it to a function?
No, that would be = function () { }.
how is that assignment different from an array?
An array has a bunch of features not found in a basic object, such as .length and a bundle of methods.
Objects are often used to store arbitrary key/value pairs. Arrays are for ordered values.
This is javascript object notation. Particularly {} means empty object, the same as new Object();. See json.org.
That would be an empty JavaScript object.
Using {} creates an object. You can use the object like a hash-map or similar to how you can use arrays in PHP.
var obj = {};
obj['test'] = 'valuehere';
obj.secondWay = 'secondValue';
and you could access them by calling obj.test and obj['secondWay'].
It's an initialized empty object, eg. an object of no particular type. It serves to provide a definition for this.materials so that the code won't have to check it for null or being defined later.
It does create an empty object.
var myObj = {};
Within an object you can define key/value pairs, e.g.:
myObj.color = 'red';
A value can be a function, too:
myObj.getColor = function() { return this.color };
It's JON (Javascript Object Notation) for creating a new empty object. Almost equal in idea to how you'd normally do Object x = new Object() in java, minus the initialization part...

Categories

Resources