Use variable for property name in JavaScript literal? - javascript

I know we can create new properties in Javascript objects during runtime but could that property be assigned a value too? For example.
var value = "New value";
var table = new Object();
var newValue = table[value];
Now, I know that value table has a new property called "value". but does that "value key contains the information as " New Value". So, does that mean now table object is like following:
table = {
value:"New Value";
}

You're confusing accessing with assigning.
// Assigns a variable named 'value' with a value of 'New Value'.
var value = "New value";
// Creates a variable named 'table' as a blank Object.
var table = new Object(); // Alternatively - table = {};
// Attempts to access "New Value" from object "table" which returns undefined.
var newValue = table[value];
If you want to assign properties to an object you do so like this:
// Assumes table is still an object.
table['key'] = 'value';
// Note that I almost _always_ opt for the variable['key'] notation over
// the variable.key notation because it allows you to use keys
// that would otherwise not be valid as identifiers.
table['Some Key'] = 'Some Value'; // This works.
table.Some Key = 'Some Value'; // This does not.
Later, when you want to retrieve that value and store it in a new variable, that's when you do this:
var newVariable = table['key'];
Hopefully that clarifies some. Please let me know if I can expand on any part of it.

no. your statement
var newValue = table[value];
is not setting anything, and since at the time when you created table you didn't assign any property, newValue will be undefined.
If you have a value variable that is assigned a value, and you want to assign that value to table under the key value, you want to do
table['value'] = value;
or alternatively
table.value = value

Erm, no, I don't think you've got it quite right.
All that does is assign undefined to newValue, because you're trying to access table's "New Value" property, which doesn't exist.
What I think you're trying to do is this:
var value = "New value";
var table = {};
table.value = value;

Related

How to add a value to an Object in javascript?

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;
}

LocalStorage, JavaScript and Objects

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.

How to set a Javascript object values dynamically?

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

How can I store reference to a variable within an array?

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.

Using variable name in JS object?

I defined a variable which will get user's input:
var input = USER_INPUT;
then, I create an object which will use this input as an variable name inside the object:
var obj = { input: Car.newCar(...)}
Then, I try to access the obj[input], but it returns to me undefined. Is it so that in javascript, I can not use variable as an object's variable name?
If I would like to define a object which has vary variable name and variable value, how can I do?
So I guess you want the store the input under a key named after the input itself.
You can assign the value returned by Car.newCar() by using the [] method:
var input = "some text";
var obj = {};
obj[input] = Car.newCar();
Sorry changed my answer after re-reading the question
var USER_INPUT = 'something';
var obj = {};
obj[USER_INPUT] = 'value';
obj.something ; //# => value
obj['something'] ; //# => value
obj[USER_INPUT]; //# => value

Categories