Trying to make a data module - javascript

I'm trying to make a data module in JavaScript, but can't access the data from outside, while everything works fine when I try to log it from inside
'use strict;'
function manager() {
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
};
manager().define('John', 'Smith', 17);
console.log(manager().get(1));
//undefined

Every time you call manager you define a new variable named data and assign it the value {}.
So manager().define('John', 'Smith', 17); creates an object, assigns some data to it, then the object drops out of scope and is garbage collected.
Then console.log(manager().get(1)); creates a new object, and it has no data in it.
Define the variable and assign the object to it outside the function.

Kindly use module pattern and the execution will like this
var manager = (function() {
'use strict';
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
}());
manager.define('John', 'Smith', 17)
console.log(manager.get(1))
var manager = (function() {
'use strict';
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
}());
manager.define('John', 'Smith', 17)
console.log(manager.get(1))

Related

How to assigning Object into another object (not merging)

var student={
student1:{
name:"John",
}
}
var student2={
name:"Doe"
}
Resultamt object should contain both student object with their object's name
Like this :-
students={
student1={name:"John"},
student2={name:"Doe"}
}
You can use object spread to solve this.
e.g
let student = {
student1: {
name: "John",
},
};
let student2 = {
name: "Doe",
};
let students = {
...student,
student2,
};
console.log(students);
Using spread operation you can combine them.
const students = {
...student1,
...student2
};

how to get an object from a closure?

How to get an object from a closure, that's confusion with me, here is the question:
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
question: How do i get original person object without changing the source code.
var o = function() {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function(key) {
return person[key]
}
}
}
Object.defineProperty(Object.prototype, "self", {
get() {
return this;
}
});
console.log(o().run("self")); // logs the object
This works as all objects inherit the Object.prototype, therefore you can insert a getter to it, which has access to the object through this, then you can use the exposed run method to execute that getter.
You can get the keys by running
o().run("<keyname>"))
Like that:
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
console.log(o().run("name"));
console.log(o().run("age"));
Could just toString the function, pull out the part you need, and eval it to get it as an object. This is pretty fragile though so getting it to work for different cases could be tough.
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
var person = eval('(' + o.toString().substr(30, 46) + ')')
console.log(person)
o().run("name")
It will be return "jonathan".
Simply you can make this
<script type="text/javascript">
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
let a = new o;
alert(a.run('name'));
</script>

How can I call an object property with a variable?

I am trying to solve an issue of calling an object property + function with string.
For example:
var myobject = {
firstName: "Bob",
lastName: "Joe"
};
var show = "lastName";
myobject[show].thisfunction();
In the console everything works as I would expect, but in code it says
Uncaught SyntaxError: Unexpected token [
Any thoughts? Thanks!
This is how it will be done
Here if How you can call the Function on it.
if you want to call the function from current class instance then just replace obj with this.
var proprt = 'firstName'
var myobject = {
firstName: "Bob",
lastName: "Joe"
};
var a =() => { alert('Hello') }
var obj = { Bob:{ thisFn: a } }
obj[myobject[proprt]].thisFn()

Concise way to declare and load object

I have an object that I am creating and a function on that object to load data into the various properties. While the method works as desired, I feel like it might be redundant. Can this be accomplished in a more concise or better way?
var user = {
productLine: {
userActiveValue: []
},
id: {
PACT: null,
EDIPI: null,
AKO: null,
},
name: {
first: null,
last: null,
},
DMIS: null,
region: null,
email: null,
load: true,
loadUser: function (userInfoAPIResponse) {
this.id.PACT = userInfoAPIResponse.UID;
this.id.EDIPI = userInfoAPIResponse.EDIPN;
this.id.AKO = userInfoAPIResponse.akoUserID;
this.name.first = userInfoAPIResponse.fName;
this.name.last = userInfoAPIResponse.lName;
this.DMIS = userInfoAPIResponse.dmisID;
this.region = userInfoAPIResponse.RHCName;
this.email = userInfoAPIResponse.userEmail;
console.log(this);
}
};
function User(userInfoAPIResponse) {
this.id = {
PACT: userInfoAPIResponse.UID,
EDIPI: userInfoAPIResponse.EDIPN,
AKO: userInfoAPIResponse.akoUserID
};
this.productLine = {
userActiveValue: []
};
this.name = {
first: userInfoAPIResponse.fName,
last: userInfoAPIResponse.lName
};
this.DMIS = userInfoAPIResponse.dmisID;
this.region = userInfoAPIResponse.RHCName;
this.email = userInfoAPIResponse.userEmail;
}
var user = new User(...);
Aside from using e.g. user.name = {first: response.fName, last: response.lName} and so on, no. You need to map the variables from one object to another yourself, or just use the response as your user variable.
Alternatively you could just declare user as global (or outer) scope and both declare and set the sub-objects in your callback function. This would mean you potentially had to check for them and their parents being undefined before using them elsewhere, as opposed to a simple not null check.

Cannot Populate Javascript Object Properties with Values Using Function

I have the following Javascript object defined:
var APIUserItem = function () {
var
id = '',
account_id = '',
client_id = '',
user_name = '',
salutation = '',
first_name = '',
middle_name = '',
last_name = '',
organization_name = '',
alternate_email = '',
time_zone_id = '',
utcoffset = '',
date_created = new Date(),
last_updated_date = new Date(),
is_active = null,
is_approved = null,
classes = [],
groups = [],
permissions = [],
properties = {},
version_stamp_hash_string = '',
getFromData = function (data) {
id = data.ID;
account_id = data.AccountID;
client_id = data.ClientID;
user_name = data.UserName;
salutation = data.Salutation;
first_name = data.FirstName;
middle_name = data.MiddleName;
last_name = data.LastName;
organization_name = data.OrganizationName;
alternate_email = data.AlternateEmail;
time_zone_id = data.TimeZoneID;
utcoffset = data.UTCOffset;
date_created = data.DateCreated;
last_updated_date = data.LastUpdatedDate;
is_active = data.IsActive;
is_approved = data.IsApproved;
properties = data.Properties;
version_stamp_hash_string = data.VersionStampHashString;
// list of pointers to classes
$.each(data.Classes, function (index, value) {
class_pointer = new APIPointerItem();
class_pointer.ID = value.ID;
class_pointer.PublicID = value.PublicID;
class_pointer.Name = value.Name;
class_pointer.RelativeURI = value.RelativeURI;
classes.push(class_pointer);
});
// list of pointers to Groups
$.each(data.Groups, function (index, value) {
group_pointer = new APIPointerItem();
group_pointer.ID = value.ID;
group_pointer.PublicID = value.PublicID;
group_pointer.Name = value.Name;
group_pointer.RelativeURI = value.RelativeURI;
groups.push(group_pointer);
});
// list of permissions
$.each(data.Permissions, function (index, value) {
permission_pointer = new APIPermissionList();
permission_pointer.ID = value.ID;
permission_pointer.Description = value.Description;
permission_pointer.Category = value.Category;
permission_pointer.Level = value.Level;
permission_pointer.ResourceType = value.ResourceType,
permission_pointer.Action = value.Action;
permissions.push(permission_pointer);
});
};
return {
ID: id,
AccountID: account_id,
ClientID: client_id,
UserName: user_name,
Salutation: salutation,
FirstName: first_name,
MiddleName: middle_name,
LastName: last_name,
OrganizationName: organization_name,
AlternateEmail: alternate_email,
TimeZoneID: time_zone_id,
UTCOffset: utcoffset,
DateCreated: date_created,
LastUpdatedDate: last_updated_date,
IsActive: is_active,
IsApproved: is_approved,
Classes: classes,
Groups: groups,
Permissions: permissions,
Properties: properties,
VersionStampHashString: version_stamp_hash_string,
GetFromData: getFromData
};
};
When I new up an APIUserItem by calling:
var user = new APIUserItem();
user.GetFromData(data);
then try to access the values in the new item like so:
document.write(user.ID);
all of the property values come back empty, except for the collections, which contain the expected data. For example, I can loop through the Groups array from outside the object and access the properties of each group to display values.
The data object I passed to the GetFromData function call contains all the data - it just seems like the assignments to the local variables are not working? I know I must have made some obvious mistake in my code. Can anyone help me find my problem?
Your assignments to the local variables are probably working, but they're just that: assignments to local variables. Your code does nothing to update the properties of the object. The fact that you create the object via that return statement that initializes properties from the local variables does not create a magic link between the local variables and the properties.
Your "getFromData" function should look something like this:
function getFromData( data ) {
this.ID = data.ID;
this.AccountID = data.AccountID;
// and so on
}
The collection properties ("classes", "groups", "permissions") worked because they're objects, and you update their contents. That part's OK. Really, you don't need those local variables at all; you can just initialize the object properties directly.

Categories

Resources