I have a constructor like this
function Employee(name, rank, mf)={
this.name=name;
this.rank=rank;
this.mf=mf;
}
How can I create a new employee and storing the name, rank, and mf in an object with the ability to change it later on? Keep in mind i'm creating the new employee through a function so i can't just create a new var manually. THx.
This is how i create a new employee
function employee(){
var name=prompt("Last, First");
var rank=prompt("Rank");
var mf=prompt("M/F");
var ID=prompt("ID");
var confirming=confirm("ID: "+ID+"Name: "+name+"Rank: "+rank+", "+mf);
if(confirming){
new Employee(name, rank, mf);
}else{
console.log("Employee addition cancled")
}
}
You have a typo in your constructor code which can cause you compilation (syntax) error. Note the equal = sign. Should be
function Employee(name, rank, mf) {
Q: How can I create a new employee and storing the name, rank, and mf in an object with the ability to change it later on?
A: You'll need to maintain a reference to that new object by storing it into a variable. You can achieve it by doing
var myEmployee1 = new Employee(...);
So from there you could access that same object through calling the variable like myEmployee.name
If you are having a function to take on the create employee object role then you can either modify that function to, return the newly created object or populate straight into a global variable. My preference would be the former as it is much cleaner.
Also, tracking the employee objects in an array is 1 strategy you can use but depending on how many objects you are expected. Finding an object in an array may not be as efficient as storing them in a {} dictionary data structure. As you are required to loop through individual objects from an array before finding the right one, whereas dictionary you access objects straight from the key, essentially transversing a tree which is quicker in most scenario.
Obviously storing an employee object through using the name as the key can be dangerous because names are never unique. Instead you should be using the unique identifier Id.
Example:
function employee(){
...
return new Employee(name, rank, mf);
}
var myDictionary = {};
var emp = employee();
myDictionary[emp.id] = emp; // Store the employee object by its key with value = the object itself.
// To access the very same employee object next time. Let say the id is 10 then you would do...
console.log(myDictionary[10].name)
You need to maintain global array for object reference this check my sample code :
var objRef=[];
function employee(){
var name=prompt("Last, First");
var rank=prompt("Rank");
var mf=prompt("M/F");
var ID=prompt("ID");
var confirming=confirm("ID: "+ID+"Name: "+name+"Rank: "+rank+", "+mf);
if(confirming){
objRef[name]=new Employee(name, rank, mf); //access using objRef['alen']
}else{
console.log("Employee addition cancelled.")
}
}
//Your constructor.
function Employee(name, rank, mf)
{
this.name=name;
this.rank=rank;
this.mf=mf;
}
and you can access your object by simply objRef[name]. you can make id as key .
Related
I have below piece of code
addToFilterCriteriaTree(componentData) {
let id = componentData.props.data.id;
this.state.filterCriteriaTree[id] = componentData.criteria;
}
Instead of state ,I want to create a object 'filterCriteriaTree' using setStorage and add a new key to it
I've changed the parameters since it's cleaner to supply only the data needed for the function to do it's job rather than the entire object.
addToFilterCriteriaTree(id, criteria) {
let currentFilterCriteriaTree = JSON.parse(sessionStorage.getItem('filterCriteriaTree')) || {};
currentFilterCriteriaTree[id] = criteria;
sessionStorage.setItem('filterCriteriaTree', JSON.stringify(currentFilterCriteriaTree);
}
Following on from this question, I would like to create a DRY way of creating Js variables for a D3 graph which represents daily sentiment analysis of UK newspapers.
Here is some example code from my script:
var guardian,independent; // many more here
var gLine,gChart; // many more here
var iLine,iChart; // many more here
I am storing the newspaper-specific variables in an object:
var allObjects = { guardian : {line : gLine,chart : gChart},
independent : {line : iLine,chart : iChart}}// and so on for each newspaper
I assign the variables using functions as follows:
function makeLine(name){return d3.svg.line().y(function(d) { return y(d[name]); }); }
// and so on for each newspaper attribute in AllObjects
Rather than repeating myself all the time, making each object individually:
makeLine('guardian'); makeLine('independent'); // etc
...which works fine, I would like to be able to iterate over all the newspapers, and assign the objects with a single function for all newspapers, something like:
var allFunctions = {line: makeLine(),chart: makeChart()};
function make(type){
var myFunc = allFunctions.type;
for(var prop in allObjects){prop.type = myFunc(type);}
}
So that make(line) would assign gLine, iLine, etc
The problem is that as the variables in allObjects.guardian are undefined, this method isn't working.
Any suggestions as how to refactor in this way?
Rather than repeating myself all the time, making each object individually:
makeLine('guardian'); makeLine('independent'); // etc
...which works fine, I would like to be able to iterate over all the newspapers, and assign the objects with a single function for all newspapers
If I'm reading that right, your "something like" is really close, see comments:
var allFunctions = {line: makeLine, chart: makeChart};
// Note no () here ----------------^ or here --------^
// We want the reference to the function, we don't want to call it (yet)
// Assuming `type` is "line", "chart", etc.
function make(type){
// Note brackets: We want the property whose name is in the type
// variable, not a property actually called "type"
var myFunc = allFunctions[type];
// ^----^------ We want the property whose name is in
// the `type` variable, not a property
// actually *called* "type"
for (var prop in allObjects) {
allObjects[prop][type] = myFunc(prop);
// ^----^-----^----------- Brackets again as above
}
}
I am looking for the correct way to store references to objects in javascript.
For example I have an object customer:
function Customer(n) {
this.name = n;
}
And an array of all customers, that gets filled:
var customers = new Array()
customers.push(new Customer('Alfred'));
customers.push(new Customer('Bob'));
Now I also have several other objects which reference customers, like purchase, and outstandingOffer, promotion ect. which should all reference to elements of the customers array. For example:
function Purchase(i, c) {
this.customer = c; // ? <- this need to be a reference
this.item = i;
}
This could be done by storing the index in the array, but that seems fragile in case a customer needs to be removed. What is the best way to store a reference to another object in javascript?
looking at below you approach is different
var customers = new Array()
customers.push(new Customer('Alfred'));
customers.push(new Customer('Bob'));
You are pushing new objects in an array without saving a reference to it.So your purchase function will never know what is who or who is what
This is How I would approach it
function Customer(n) {
this.name = n;
this.items=[];
this.addPurchase=function(item){
this.items.push(item);
}
}
The above function will have the follow
The name of the customer
A function that adds an item to the customer item cart
An item cart
var customers = {}; //create a big object that stores all customers
customers.Alfred=new Customer('Alfred'); // create a new object named Alfred
customers.Bob=new Customer('Bob'); // create a new object named Bob
customers.John=new Customer('John'); // create a new object named John
Using console.log, you will get
Alfred: Object, Bob: Object, John: Object
If you want to add items to Alfred you do this
customers.Alfred.addPurchase('pineapple');
If you want to add items to Bob you do this
customers.Bob.addPurchase('mango');
If you want to add items to John you do this
customers.John.addPurchase('coconut');
This is output from console.log(customers.John.items);
Array [ "coconut" ]
So what if we want to delete a customer?
We already have a reference to it!
delete customers.John;
John and this history is gone!...Verify it is deleted
console.log(customers);
output
Object { Alfred: Object, Bob: Object }
use new to create object
var customers = new Array()
customers.push(new Customer('Alfred'));
customers.push(new Customer('Bob'));
function Purchase(i, c) {
this.customer = c; // ? <- this need to be a reference
this.item = i;
}
var Purchase_obj = new Purchase(2,customers[0] );
I'm creating a very simplified version of a drag and drop shopping cart with jqueryui.
My issue is regarding adding data(id, name, price) to an array.
I tried several methodes of adding the data (also an array) to the main container(array). But I keep getting this error: Uncaught TypeError: undefined is not a function
var data = [];
function addproduct(id,name,price){
//var d = [id,name,price];
data[id]["name"] = name;
data[id]["price"] = price;
data[id]["count"] = data[id]["count"]+1;
console.log(data);
}
the addproduct() function can be called by pressing a button
It is not entirely clear to me what type of data structure you want to end up with after you've added a number of items to the cart. So, this answer is a guess based on what it looks like you're trying to do in your question, but if you show a Javascript literal for what you want the actual structure to look like after there are several items in the cart, we can be sure we make the best recommendation.
You have to initialize a javascript object or array before you can use it. The usual way to do that is to check if it exists and if it does not, then initialize it before assigning to it. And, since you're keeping a count, you also will want to initialize the count.
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id]["name"] = name;
data[id]["price"] = price;
++data[id]["count"];
console.log(data);
}
And FYI, arrays are used for numeric indexes. If you're using property names like "name" and "price" to access properties, you should use an object instead of an array.
And, I would suggest that you use the dot syntax for known property strings:
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id].name = name;
data[id].price = price;
++data[id].count;
console.log(data);
}
It looks like what you want is an array of objects, although I would need a more detailed description of your problem to be clear.
var data = []
function addproduct(id, name, price)
{
data.push({'id': id, 'name':name, 'price': price, 'count': ++count});
console.log(data);
}
Object :
var userData = {
"a1":{"a":"1"},
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
};
I need to delete Object with key "a1" and place a new object i.e. "f6" at same place.
i.e.
userData["f6"] = userData["a1"];
userData["f6"].new = "true";
delete userData["a1"];
Output:
userData = {
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
"f6":{"a":"1", new:true},
};
Expected O/p:
var userData = {
"f6":{"a":"1", new:true},
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
};
Thanks in Advance..
In Javascript, objects have no specific order for their properties. When you see them as a JSON, the properties are shown in the same order they where declared or added. To mantain a specific order, you may do changes in your object and implement an Array.