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] );
Related
I'm trying to achieve the following Array/Object,
[
1:[{data:data},{data:data}]
]
How would this be achieved?
I got thus far,
var data = [];
data['1'] = {data:data}
but this just overwrites.
The notation [] is for making Arrays, {} is for making Objects.
See the following
const data = {}; // Initialize the object
data['1'] = []// Makes data={'1':[]}
data['1'].push({data: 'data'}) // Makes data = {'1':[{data:'data'}]}
OR
const data = []; // Initialize the Array
data.push([]) // Makes data=[[]]
data[0].push({data: 'data'}) // Makes data = [[{data:'data'}]]
If i get you right you want to push objects into an array inside of an hashtable ( which can be easily implemented using an object in javascript).
So we need an object first:
const lotteries = {};
Now before storing data, we need to check if the relating array exists, if not we need to create it:
function addDataToLottery(lottery, data){
if(!lotteries[lottery]){ //if it doesnt exist
lotteries[lottery] = []; //create a new array
}
//As it exists definetly now, lets add the data
lotteries[lottery].push({data});
}
addDataLottery("1", { what:"ever"});
console.log(lotteries["1"]));
PS: If you want to write it in a fancy way:
class LotteryCollection extends Map {
constructor(){
super();
}
//A way to add an element to one lottery
add(lottery, data){
if(!this.has(lottery)) this.set(lottery, []);
this.get(lottery).push({data});
return this;
}
}
//Create a new instance
const lotteries = new LotteryCollection();
//Add data to it
lotteries
.add("1", {what:"ever"})
.add("1", {sth:"else"})
.add("something", {el:"se"});
console.log(lotteries.get("1"));
based on this answer, I want to convert store data to object and defined the key value as well. Here's my related code :
var recordArray = {};
var paramArray = [];
store.each(function(record){
recordArray.comment = record.get("comment");
recordArray.datecreated = record.get("datecreated");
paramArray.push(recordArray);
});
console.log(Ext.encode(paramArray));
But the printed out is only last data from store, with sum matches with data sum. Suppose I have 2 data from list view like this :
[{comment: a, datecreated:1-2-1999}, {comment: b, datecreated:2-2-1999}]
The print out :
[{comment: b, datecreated:2-2-1999}, {comment: b, datecreated:2-2-1999}]
What I want, of course, the paramArray contains every object of listView, not just a same one. Any ideas? Help appreciated.
Try this,
var paramArray = [];
store.each(function(record){
var recordArray = {};
recordArray.comment = record.get("comment");
recordArray.datecreated = record.get("datecreated");
paramArray.push(recordArray);
});
In your code, you are overwriting the values in the original recordArray object instead of creating a new object everytime and since objects are passed by reference in JavaScript, the original recordArray reference at paramArray[0] also gets modified.
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 .
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.
I'm trying to learn JavaScript. I'm working on a problem where I'm making a grocery list: an array of sub-arrays that contain item, quantity and price. From there I plan to add items, read back the list, remove items, etc. My current issue is I cannot access sub-methods. I can't seem to find documentation on how to do it - but I keep reading that these methods are private? So maybe I'm way off base. I can't figure out how else I could set this up so multiple methods all talk to each other.
var groceryList = function(food, quantity, price) {
this.item = {};
this.items = {food:food, quantity:quantity, price:price};
return this.items
this.addStuff = function(food, quantity, price) {
this.items.push({food:food, quantity:quantity, price:price});
return this.items
};
this.tallyList = function() {
return items.length;
}
}
var myList = new groceryList("cookie", 2, 1.00);
console.log(myList)
myList.addStuff("brownie", 1, 2.50);
console.log(myList.tallyList);
var groceryList = function(food, quantity, price) {
this.items = [];
this.items.push({food:food, quantity:quantity, price:price});
var that = this;
this.addStuff = function(food, quantity, price) {
that.items.push({food:food, quantity:quantity, price:price});
return that.items;
};
this.tallyList = function() {
return that.items.length;
};
this.getItems = function() {
return that.items;
};
return this;
};
var myList = new groceryList("cookie", 2, 1.00);
console.log(myList);
myList.addStuff("brownie", 1, 2.50);
console.log(myList.tallyList());
This is the correct(-ish) version of what you are trying to accomplish.
Issues with your code:
this.items should be any array, not an object. Notice the square brackets, instead of curly braces.
Your constructor (the groceryList function) is not returning the entire class - it's returning just the list/array. So you cannot call myList.addStuff() or myList.tallyList() - they don't exist!
Please checkout How does the "this" keyword work?. Unlike other OO languages, "this" in JS does NOT refer the current "instance" but the current "scope".
This page describes the usage of "this" better than I could :-)
I have added an extra function (getItems()) - you can now fetch the array of items with
myList.getItems()
That code is kind of weird.
A list is an array in JavaScript and each item in the list you can treat it as an object just as you are doing it.
In your example, groceryList is an object that defines private "methods". Convention in JavaScript and many other programming languages is to name "classes" as UpperCamelCase, so groceryList is GroceryList.
Inside the "function" GroceryList this means the object itself, so you can attach it functions like this.addStuff = function ... or "properties" this.items = []. Arrays variables always call them in plural because they contain a collection of stuff.
this.items is an array (list) of groceries and each grocery has 3 properties: food, quantity and price. And you can add them to they array with the array method this.items.push(grocery) where grocery is a grocery object.
var GroceryList = function() {
this.items = []; // array to store groceries
// add to object method to add groceries to list
this.addStuff = function(food, quantity, price) {
this.items.push({
food: food,
quantity: quantity,
price: price
});
};
};
var groceryList = new GroceryList();
groceryList.addStuff('cookie', 2, 1.00);
groceryList.addStuff('brownie', 1, 2.50);
console.log(groceryList.items);
There is nothing private in this "class". Don't worry about that.
Fiddle to play with http://jsfiddle.net/42cna2d3/.