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.
Related
I have a JavaScript array and I want to get the value of last name from it.
Can anyone tell how to get that from this array example:
var result = [{"FirstName":"paapu","LastName":"gandhi"}];
You have an array containing an object, so you have to retrieve the object by doing:
var myObj = result[0]
And then get the LastName property by:
var lastname = myObj.LastName
Get the first object.
var obj = result[0];
Refer to the property of the object:
var prop = result[0].FirstName;
If property name comes dynamically, that is, from a variable, use square bracket notation.
var myVar = "FirstName";
var prop = result[0][myVar];
Let's take an example in javascript
var b = function(){
var key = {};
var result = [];
var a =
[{people: "people1"},
{people: "people2"},
{people: "people2"},
{people: "people3"}]
for(i=0;i<a.length;i++)
{
var val = a[i][people];
if(angular.isUndefined(key[val]))
{
Key[val] = "abc"; /////This line is foreign to my knowledge.
result.push(val);
}
}
return result;
}
Now in this Example i am creating an object Key and a array result.
The for loop will loop through the a variable and store the value of people property in the var val.
The angular.Isundefined function check whether the key[val] contains any duplicate data if not then it will add using the
Key[val] = "abc".
1) Now i have no idea how this line is creating the value and key pair in the key object.
2) Please tell me other ways to add value to the object.
O/P is as follows
key = Object {people1: abc, people2: abc, people3: abc}
hence it is adding value to key object without duplicating the value.
P.S. it is just an example not the real code.
From the link of Andreas in comments
I think this solves my problem.
the other way to add the key and value to the JSON object is like this.
obj = {};
obj[people1] = "data";
obj[people2] = "data";
obj[people3] = "data";
console.log(obj);
The key cannot be same but the value can be same.
So this is what my question was
Key[val] = "abc";
this line is getting the val variable dynamically and adding the val variable as the key and the value is abc.
Twist:
Do you think that
key.val = "abc";
work?
No:
This is what provided by the site
Any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number)
can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
in the following example i add count in my json my json come from ajax but i want to add count so add count below code that's work fine for me here .count is my custom value added by me, it is not part of my response
$scope.data = response.items;
for (var i = 0; i < response.items.length; i++) {
response.items[i].count = i;
}
Does anyone know what is test[name] mean?
function test(value){
copy(value||{},this);
}
test[name] = function(){
return "test"
}
This will be easiest to explain with an example:
var name = "foo";
test[name] = function(){
return "test"
};
This would add a property named "foo" to the object test, and the value of that property is a function. It doesn't matter in this case that the object test is actually a function, you can assign properties to functions just like any other object in JavaScript.
You could call this function using any of the following methods:
test[name]()
test["foo"]()
test.foo()
Note that test[name]() will not work if the name variable is assigned to something different, for example name = 'bar'.
Javascript has two sets of notation for accessing objects, dot notation (obj.property) and bracket notation (object[property]). More on that at MDN.
test[name] = function (){} assigns an anonymous function to the name property on the the test object (which itself is a function). In this case (as noted by the comments) the variable name is being used to access the property.
This may seem a little strange at first, but it's helpful to remember that in javascript, functions are objects.
All functions in Javascript are also objects. This adds a property to the test function object with a value which is an anonymous function.
For example:
function test(){
return "foo";
}
// test is a function, so it is also an object and
// it can have properties assigned to it
test.x = function(){
return "bar";
};
test(); // "foo"
test.x(); // "bar"
Of course just like with any object you can also use bracket notation:
var name = 'hello';
test[name] = function(){
return "HELLO!";
};
test.hello(); // "HELLO!"
In JavaScript, functions are objects. They have properties. test[name] sets a property (named whatever the name variable holds) to a function.
when you have a javascript object with defined properties you can access the property either with the dot notation obj.property or with the square brackets notation obj[property]
the property could also be a function so if you have an object:
var test = {
foo : function(arg){ console.log(arg) },
bar : 'hello'
};
you can call test.foo('bar') also by doing test['foo']('bar')
This is especially useful in iterations or when you dont know a priori what the name of the property is going to be. For example:
var fun = 'foo';
test[fun]('hello world');
Naturally it's up to you to do proper checks such as
if ('function'==typeof test['foo']){ test['foo']('bar'); }
Also note that you can do checks on the fly like so:
test[ fun || 'foo']('hello');
Taken from the Mozilla page
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of object members
There are two ways to access object members: dot notation and bracket notation (a.k.a. subscript operator).
So
test[name] = function (
means: there are (if everything is ok) two objects: test and name (and we know that at least test is present, because you defined it one line before: function test(value))
take the test object (if there isn't a test object an error will happen). Then access the key/value pair with the key calculated from the name object and there put a function.
Now, how the key is calculated from the name object? The same page from before tells us:
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
Note that the description is a little wrong... test[null] == test["null"] and test[undefined] == test["undefined"], so perhaps the truth is that under the covers something like String(key).valueOf() is done (the String function will convert null to "null" and undefined to "undefined")
Some examples (where => means "is equivalent to, with this values")
var name = 'foo';
test[name] => test['foo']
var name = 123;
test[name] => test['123']
var name = 123.3;
test[name] => test['123.3']
var name = new Date();
test[name] => test['Wed Aug 14 2013 17:35:35 GMT+0200 (...)']
var name = null;
test[name] => test['null']
var name = undefined;
test[name] => test['undefined']
var name = [];
test[name] => test['']
var name = [1,2,3];
test[name] => test['1,2,3']
var name = {};
test[name] => test['object Object']
and so on...
The brackets are how you reference a property via a key into the hash that javascript objects are.
I would like to access the object provided only it's string path in form of array is known.
1.) there is an object, where
root["obj1"]["obj2"] = 1;
(in common case root["obj1"]...["objN"])
2.) I have ONLY string objectPath known:
var objectPath = 'root["obj1"]["obj2"]'
3.) I need NOT only READ the object, but SET it's value, like
objectPath = 2;
//so root["obj1"]["obj2"] === 2
As I understand
there might be some options with eval(), but it gets the value, not the variable;
one can loop through all objects of root, make convertion to "root.obj1.obj2" (which is not the case, as "obj1" can easily be "obj with spaces1") and check if given string equals to current object in the loop.
http://jsfiddle.net/ACsPn/
Related Link:
Access object child properties using a dot notation string
I wrote a function for you, trying to make it as pretty and reusable as possible :
function setProp(path, newValue, holder) {
var t = path.split(/[\[\]"]+/).filter(function(v){return v}),
l = t.pop(), s, o = holder || window;
while (s = t.shift()) o = o[s];
o[l] = newValue;
}
You use it like this :
setProp('root["obj1"]["obj2"]', 2);
If your root object isn't in a global variable, pass the relevant holder as third argument.
Demonstration (open the console to see the changed root object)
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.