Set a property as reference to an object - javascript

I have a table that have a property named "recordsource" that will hold the name of the object that will fill the content of the table.
<table id="tbl" recordsource="myobj">
Now here are my functions:
var myobj;
function obj()
{
this.code = new Array();
this.name = new Array();
}
myobj = new obj();
myobj.code = ["a","b","c"];
myobj.name = ["apple","banana","carrot"];
function populate_table()
{
mytable = document.getElementById("tbl");
mytableobj = mytable.getAttribute("recordsource"); //this will return a string
//my problem is how to reference the recordsource to the myobj object that have
//the a,b,c array
}

try this window[ mytableobj ] it will return myobj

One way is to use an object as a list of all the other objects that you want to be able to access.
...
var obj_list = {
'myobj': myobj
};
function populate_table()
{
mytable = document.getElementById("tbl");
mytableobj = mytable.getAttribute("recordsource");
// Then obj_list[mytableobj] == myobj
obj_list[mytableobj].code[0] // Gives "a"
obj_list[mytableobj].name[0] // Gives "apple"
}

Related

Getting the object variable name for the new object

I have an object constructor such as:
function myObjConstr () {
console.log(object_name);
}
I want this results:
var name1 = new myObjConstr(); //print in console log "name1"
var nameff = new myObjConstr(); //print in console log "nameff"
You would need to pass the object name to the constructor:
function myObjConstr (obj_name) {
this.object_name = obj_name;
console.log(this.object_name);
}
var name1 = new myObjConstr("name1");
var nameff = new myObjConstr("nameff");
you can make a function constructor myObjConstr(), thenafter you can make new myObjConstr().
1) function constructor
function myObjConstr (objName) {
this.objName = objName;
}
2) make object of type myObjConstr
var name1 = new myObjConstr("name1");
var name2 = new myObjConstr("name2");
3) if you want to print the value,
console.log(name1.objName)
You can't pass the variable name to the constructor. Instead you can convert an array of names of variables to array of objects
let names = [
'name1',
'nameff'
]
let objects = names.map(name => myObjConstr(name));
function myObjConstr(name){
this.name = name;
console.log(this.name);
}

Copy object functions and properties in new object by value not by reference - javascript

I want to copy the functions and properties of an object into new object. The old object should not effect by changing made in new Object.
Here is the object definition:
var Call = function() {
this.number="123";
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
I can access function1 using callobj.function1().
What I have tried to copy it:
Javascript:
var newcallobj = Object.assign({}, callobj);
In this case, i am not able to access function1 but i can access number property directly.
JQUERY:
var newObj = jQuery.extend(true, {}, callobj); OR
var newObj = jQuery.extend({}, callobj);
In this case, i am able to access function1 and property but when i change number like that newObj.number="222". It also change the value of original object.
I know that there is couple of other posts. But all is not working for me. Please let me know if i am doing any thing wrong?
AFTER #gurvinder372 answer(I am updating question):
After #gurvinder372 answer. It is working for first level of property but if it has another object like i show below and i change the value of property of another object. Then it is effecting on original object also.
var ABC = function(){
this.number = "333";
}
var Call = function() {
this.number="123";
this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);
Output of both is 123. #gurvinder372. can you check th above code ?
Object.assign only copies the enumerable properties of an object.
Use Object.create instead of Object.assign
var newcallobj = Object.create(callobj);
var Call = function() {
this.number="123";
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
console.log(newcallobj.function1());
Ok. By the help of #gurvinder372. The following solution is working for me.
var ABC = function(){
this.number = "333";
}
var Call = function() {
this.number="123";
this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj = Object.create(callobj.anotherobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);
Please let me know if there is any better solution other than this?

Adding protos but keeping object structure, javascript

Lets say I get this from an API:
var _persons = [
{
name: 'John'
},
{
name: 'Sarah'
}
];
Now I want to add a greeting function. I want to save memoryspace so I create a Person 'class' and add the function as a proto.
function Person(person){
this.person = person;
}
Person.prototype.greeting = function(){
return 'hello ' + this.person.name
};
I instantiate each person:
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]);
persons.push(person);
}
};
createPersons(_persons);
Problem is this:
console.log(persons[0].name) //undefined
console.log(persons[0].person.name) //'John'
Is there anyway I can get the first console.log to work?
https://jsbin.com/zoqeyenopi/edit?js,console
To avoid the .person appearing in the object you need to copy each property of the source plain object directly into the Person object:
function Person(p) {
this.name = p.name;
...
}
[or use a loop if there's a large number of keys]
You've then got a mismatch between the named parameter and the variable you're iterating over in the createPersons function. Additionally it would make more sense to have that function return the list, not set an externally scoped variable:
function createPersons(people) {
return people.map(function(p) {
return new Person(p);
});
}
var persons = createPersons(_persons);
NB: the above uses Array.prototype.map which is the canonical function for generating a new array from a source array via a callback.
Loop over all the keys in your object argument and assign them to this
function Person(person){
for (var key in person) {
this[key] = person[key];
}
}
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]);
persons.push(person);
}
};
createPersons(_persons);
Should be using people as a variable
You're creating a Person object that is given a variable person. You need to change the value you're getting by replacing
var person = new Person(people[i]);
with
var person = new Person(people[i]).person;
var _persons = [
{
name: 'John'
},
{
name: 'Sarah'
}
];
function Person(person){
this.person = person;
}
Person.prototype.greeting = function(){
return 'hello ' + this.person.name;
};
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]).person;
persons.push(person);
}
};
createPersons(_persons);
console.log(persons[0].name); // logs 'John'
document.write('John');

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]

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

Categories

Resources