Javascript: Object attribute declaration from variable - javascript

I am aware I can use another object's property as a key to declare a property of the object, like so:
var object1 = {
myAttr: 'myName'
};
var object2 = {};
var object2[object1.myAttr] = 'myValue';
Then we have object2.myName == 'myValue'.
How would I go about doing that directly in the object's declaration? Something like that:
var object1 = {
myAttr: 'myName'
};
var object2 = {
object1.myattr: 'myValue'
};
But that actually works.

You could change your code a bit and do this:
var object1 = {
myAttr: 'myName'
};
var object2 = new function(){
this[object1.myAttr] = 'myValue'
}();
You can evolve this and pass object1 as an attribute to the object2 function and things go on...

You can do using eval function of javascript
var object1 = { myAttr: 'myName' };
eval("var object2 = { "+object1.myAttr+": 'myValue' }");
console.log(object2.myName);

Related

JAVASCRIPT: Push object to array [duplicate]

I'm trying to create a dictionary object like so
var obj = { varName : varValue };
What I'm expecting is if varName='foo', the obj should be {'foo', 'some value' } however what I see is {varName, 'some value'} the value of variable is not being used but a variable name as a key. How do I make it so that varible value is used as key?
Try like this:
var obj = {};
obj[varName] = varValue;
You can't initialize objects with 'dynamic' keys in old Javascript. var obj = { varName : varValue }; is equivalent to var obj = { "varName" : varValue };. This is how Javascript interprets.
However new ECMAScript supports computed property names, and you can do:
var obj = { [varName]: varValue };
Starting with ECMAScript 2015, which has gotten better browser support in the last year(s), you can use the variable index notation:
const obj = { [varName] : varValue };
This is syntactically the same as
var obj = {};
obj[varName] = varValue;
You can also use expressions or Symbols as property key:
const contact = {
company: companyName,
};
const companiesWithContacts = {
[contact.company.toLowerCase()]: true
};
const myList = {
[Symbol.iterator]: createIteratorForList
};
function createIteratorForList() { ... }

Concatenate object field with variable in javascript

I'm building an object in javascript to store data dynamically.
Here is my code :
var id=0;
function(pName, pPrice) {
var name = pName;
var price = pPrice;
var myObj = {
id:{
'name':name,
'price':price
},
};
(id++); //
console.log(myObj.id.name); // Acessing specific data
}
I want my id field to be defined by the id variable value so it would create a new field each time my function is called. But I don't find any solution to concatenate both.
Thanks
You can create and access dynamicly named fields using the square bracket syntax:
var myObj = {};
myObj['id_'+id] = {
'name':name,
'price':price
}
Is this what you want ?
var myObj = {};
myObj[id] = {
'name':name,
'price':price
};
console.log(myObj[id]name); // Acessing specific data
You can use [] to define the dynamic property for particular object(myObj), something like
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
Example
function userDetail(id, nom, prix) {
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
return myObj;
}
var objA = userDetail('id1', 'sam', 2000);
var objB = userDetail('id2', 'ram', 12000);
var objC = userDetail('id3', 'honk', 22000);
console.log(objA.id1.nom); // prints sam
console.log(objB.id2.nom); // prints ram
console.log(objC.id3.prix);// prints 22000
[DEMO]

Setting state of javascript function not saving

I am trying to create a new function, MyNs.MyObj(), call a method on it that modifies a 'private' variable, 'prop1', and the next time I access the public accessor, 'Prop1' that it retrieves the saved variable.
After running the below code, the output is still, '2' (the initial value). Can someone help me understand why calling the Method function does not udpate the Prop1 variable the way I expect?
var MyNs = MyNs || {};
(function( o ){
o.MyObj = function (options) {
var prop1 = options;
var obj = {
Prop1: prop1,
Method: function() {
prop1 = "abc";
}
};
return obj;
};
})(MyNs);
var s = new MyNs.MyObj(2);
s.Method();
console.log(s.Prop1);
When you do this
var prop1 = options;
var obj = {
Prop1: prop1
};
You've set Prop1 to the value of prop1 at that time, changing prop1 later will not update Prop1.
You can easily test this with something like
var a = 'abc'; // set a value on 'a'
var b = a; // set 'b' to equal 'a', as it's a string, it's passed directly
a = 'bca'; // set a new value for 'a'
alert(b); // still outputs 'abc'
FIDDLE
This means you have to update the property, not the variable, and you'd do that like so
var MyNs = MyNs || {};
(function( o ){
o.MyObj = function (options) {
var prop1 = options;
var obj = {
Prop1: prop1,
Method: function() {
this.Prop1 = "abc";
}
};
return obj;
};
})(MyNs);
var s = new MyNs.MyObj(2);
s.Method();
console.log(s.Prop1);
FIDDLE

Array of objects in js?

It's a silly question, but is this an array of objects in js?
var test =
{
Name: "John",
City: "Chicago",
Married: false
}
if so, how do I declare a new one.. I dont think
var test = new Object();
or
var test = {};
is the same as my example above.
No.
That's an object with three properties.
The object literal is just a shortcut for creating an empty object and assigning properties:
var test = { }; //or new Object()
test.name = "John";
test.city = "Chicago"
test.married = false;
An array of objects would be
myArray = [
{ prop1 : "val1", prop2 : "val2" },
{ prop1 : "A value", prop2 : "Another value" }
]
You would access the first object's prop2 property like this
myArray[0].prop2
"if so, how do I declare a new one?"
To do what I think you want you would have to create an object like this
var test = function() {
this.name = "John";
this.city = "Chicago";
this.married = false;
}
var test2 = new test();
You could alter the properties like this
test2.name = "Steve";
You can create an array of your objects like this
myArray = [test, test2];
myArray[1].married = true;
No, it's an object.
You could create an array of objects like this:
var array_of_objects = [{}, {}, {}];
For creating new objects or arrays I would recommend this syntax:
var myArray = [];
var myObject = {};
No, test is an object. You can refer to it's instance variables like so:
var myname = test.Name;
It is an object, but you must also understand that arrays are also objects in javascript. You can instantiate a new array via my_arr = new Array(); or my_arr = []; just as you can instantiate an empty object via my_obj = new Object(); or my_obj = {};.
Example:
var test = [];
test['name'] = 'John';
test['city'] = 'Chicago';
test['married'] = false;
test.push('foobar');
alert(test.city); // Chicago
alert(test[0]); // foobar

javascript 'this' usage

let's say I have code like this:
var object1 = {};
object1.class1 = function() {
this.property1 = null;
this.property2 = 'ab';
}
in this case, what does 'this' stand for? object1 or class1? And whenever I want to define a class constructor inside an object, what is the best way to do it?
For class1, because you can't make an object of type object1.
However, if the code would be:
function object1() {
this.class1 = function() {
this.property1 = null;
this.property2 = 'ab';
}
}
You could have:
var obj = new object1();
obj.class1();
obj.property2; // => 'ab';
var cls = new obj.class1();
cls.property2; // => 'ab';
So it could depend on context.
If you call it like so:
object1.class1();
Then this will refer to object1.

Categories

Resources