I have a variable containing a string "Y.Plugin.abcd" and I would like to access an object with the same name...I'm using YUI 3 and attempted the Y.namespace method with no luck.
var nm = "Y.Plugin.abcd";
Y.log(Y.Plugin.abcd); //outputs the correct object
Y.log(Y.namespace(nm)); //outputs an empty object
I'm pretty much looking for any method, YUI or not, to be able to do what is a rather simple task in PHP.
In plain JavaScript, you could probably split your string and then use the subscript notation, as follows:
var nm = "Y.Plugin.abcd";
var nm_array = nm.split('.'); // split the nm string
var obj = window; // set our reference to the global object
for (var i = 0; i < nm_array.length; i++) {
obj = obj[nm_array[i]]; // walk through all the namespaces
}
Y.log(obj); // obj will hold a reference to Y.Plugin.abcd
Related
I have generated a json-type variable:
var jsonLines = [[{"x":"275","y":"231"},{"x":"124","y":"237"}],[{"x":"201","y":"157"},{"x":"275","y":"231"}],[{"x":"215","y":"307"},{"x":"201","y":"157"}],[{"x":"342","y":"188"},{"x":"215","y":"307"}]];
I want to parse this JSON-like object and print the corresponding entities. I tried many solutions of similar problems here at SO, but nothing worked on this ( for each loop, by indexing etc.). It'll great if anyone could help me out. Thank you.
JSON is short for JavaScript Object Notation. What you have there is a Javascript object literal , and it can be treated as such.
for(var i = 0; i < jsonLines.length; i++){
var innerArray = jsonLines[i];
for(var j = 0; j < innerArray.length; j++){
var obj = innerArray[j];
//now you can use obj.x, obj.y etc...
}
}
JSON is heavily based off JavaScript object literals so when it is in actual code and not in a string/text file, it is actually a JavaScript object.
You can break-down the object like so
//An Array of...
[
//Arrays of
[
//JavaScript Object Literals
{"x":"275","y":"231"},
{"x":"124","y":"237"}
],
[{"x":"201","y":"157"},{"x":"275","y":"231"}],
[{"x":"215","y":"307"},{"x":"201","y":"157"}],
[{"x":"342","y":"188"},{"x":"215","y":"307"}]
]
Also worth nothing that JavaScript Object property names can be strings
var obj1 = {
a : "someValue"
}
var obj2 = {
"a" : "someOtherValue"
}
//Both of these objects can access property "a"
obj1.a //someValue
obj2.a //someOtherValue
I want to create an object that has some keys which come from a variable parameter.
Let's say for example that prod_id below is a variable containing some value... I want to create an object which has an attribute with key of that 'prod_id' and value of 1. However this does not work? Is this possible to achieve? if so, how? thanks a heaps
var cart_obj;
cart_obj = {
prod_id : 1
};
localStorage.setItem("cart", JSON.stringify(cart_obj));
You can't do it with a simple object literal. You can do this however:
var cart_obj = {};
cart_obj[prod_id] = 1;
JavaScript object literal syntax makes no provisions for expressions on the left side of a property declaration stanza.
var cart_obj = {};
cart_obj.prod_id = 1;
or
var cart_obj = {};
cart_obj[prod_id] = 1;
I need to store an object in localStorage - and I know that in order to do so, I have to convert the object into a string. All cool.
My problem is in actually creating the object in the first place: I have two values in sessionStorage that need to be added to the object which is then passed into localStorage. However, when I try to create the object, one value is being stored as the variable name rather than its (numeric) value. Any idea whats going on here?
var siteName = sessionStorage['1'];
var siteID = (+sessionStorage['2']);
var temp = {siteID:siteName};
alert(typeof siteID);
alert(JSON.stringify(temp));
The first alert confirms that siteID is indeed a number type, but the second alert shows that the variable name (siteID) is stored rather than its numeric value.
This line:
var temp = {siteID:siteName};
...creates an object containing a property called siteId with the value taken from the siteName variable.
If you want the property name to be taken from the siteID variable instead:
var temp = {};
temp[siteID] = siteName;
Or in ES2015 (aka "ES6") you could use the new computed property name syntax:
// ES2015+ only!
var temp = {[siteId]: siteName};
In JavaScript, you can access/create properties on objects in two different but equal ways: Using dotted notation with a literal property name:
obj.foo = "bar"; // Creates a `foo` property on `obj` with the value `"bar"`
...or using bracketed notation and a string:
obj["foo"] = "bar"; // Does the same thing
The keys in object initializers like your var temp = {siteID:siteName}; are always used literally (although they can optionally be in quotes); there's no way with an object initializer to have a key taken from a variable instead. So you have to do it as a two-step process, first create the object, then set the property.
So, if you do
temp[siteID] = siteName;
...the number in siteID will be converted to a string and will become the property name, with the value of siteName being the value.
var temp = {};
var key = 1;
temp[key] = "value";
console.log(temp[1]); // "value"
console.log(temp["1"]); // "value"
(Property names are always strings in JavaScript [for now].)
Change it to this.
var temp = {};
temp[siteName] = siteID;
Or if the typeof test was meant to show the property name, you'd reverse them.
var temp = {};
temp[siteID] = siteName;
But be aware that siteID is considered a String from that point forward.
I'm trying to create an array that maps strings to variables. It seems that the array stores the current value of the variable instead of storing a reference to the variable.
var name = "foo";
var array = [];
array["reference"] = name;
name = "bar";
// Still returns "foo" when I'd like it to return "bar."
array["reference"];
Is there a way to make the array refer to the variable?
Put an object into the array instead:
var name = {};
name.title = "foo";
var array = [];
array["reference"] = name;
name.title = "bar";
// now returns "bar"
array["reference"].title;
You can't.
JavaScript always pass by value. And everything is an object; var stores the pointer, hence it's pass by pointer's value.
If your name = "bar" is supposed to be inside a function, you'll need to pass in the whole array instead. The function will then need to change it using array["reference"] = "bar".
Btw, [] is an array literal. {} is an object literal.
That array["reference"] works because an Array is also an object, but array is meant to be accessed by 0-based index. You probably want to use {} instead.
And foo["bar"] is equivalent to foo.bar. The longer syntax is more useful if the key can be dynamic, e.g., foo[bar], not at all the same with foo.bar (or if you want to use a minimizer like Google's Closure Compiler).
Try pushing an object to the array instead and altering values within it.
var ar = [];
var obj = {value: 10};
ar[ar.length] = obj;
obj.value = 12;
alert(ar[0].value);
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called myTarget, then use:
myRef = function (newVal) {
if (newVal != undefined) myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(<the value you want to set>);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray[0]() to read and myArray[0](<new value>) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called 'myTarget', then use:
myRef = function (newVal) {
if (newVal != undefined)
myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(value_to_set);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray0 to read and myArray[0](value_to_set) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.
I'm trying to write a function that takes a string representing a namespace (e.g. "MyCompany.UI.LoginPage") and defines each segment of the namespace as an object if it doesn't already exist. For example, if "MyCompany.UI.LoginPage" wasn't an object, it would evaluate this:
MyCompany = {};
MyCompany.UI = {};
MyCompany.UI.LoginPage = {};
I would like to do this by enumerating each character of the "namespace" (string) argument and defining each object as the enumeration reaches period characters.
How can I enumerate the characters of a string in JavaScript?
You can access the characters of a string directly by its index, using the String.prototype.charAt method:
var str = "foo";
for (var i = 0; i < str.length; i++) {
alert(str.charAt(i));
}
But I don't think that you want to traverse your namespace string character by character, you can use the String.prototype.split method, to get an array containing the namespace levels using the dot (.) character as a separator, e.g.:
var levels = "MyCompany.UI.LoginPage".split('.');
// levels is an array: ["MyCompany", "UI", "LoginPage"]
But I think your question goes further to this, and I will give you a more advanced starting point, I made a recursive function that will allow you to do exactly what you want, initialize several nested object levels using a string:
Usage:
initializeNS('MyCompany.UI.LoginPage');
// that will create a MyCompany global object
// you can use it on an object to avoid globals also
var topLevel = {};
initializeNS('Foo.Bar.Baz', topLevel);
// or
var One = initializeNS('Two.Three.Four', {});
Implementation:
function initializeNS(ns, obj) {
var global = (function () { return this;})(), // reference to the global object
levels = ns.split('.'), first = levels.shift();
obj = obj || global; //if no object argument supplied declare a global property
obj[first] = obj[first] || {}; // initialize the "level"
if (levels.length) { // recursion condition
initializeNS(levels.join('.'), obj[first]);
}
return obj[first]; // return a reference to the top level object
}
You will have to improve this function, for example you will need to sanitize the string...
Convert the string into an array of characters with this code:
var $letterArray = [];
for (var $i = 1; $i <= $yourString.length; $i++)
{
$letterArray[$i] = $yourStringtring.substring(($i - 1), $i);
}
Then you can enumerate over each character in the string array $letterArrary