I have a simple time entry form, see here: https://codepen.io/dikuw/pen/rmpozm
I want to store the time data dynamically as the user adds, modifies, and deletes rows and am thinking objects is the best approach.
My question is what is the best practice? Should I create a constructor, e.g.
function TimesheetRecord(id, TSDate, TSStaffId, Hours, Comments, TSTaskId, Billable) {
this.id = id;
this.TSDate = TSDate;
this.TSStaffId = TSStaffId;
this.Hours = Hours;
this.Comments = Comments;
this.TSTaskId = TSTaskId;
this.Billable = Billable;
}
and then dynamically create a new object every time the user adds a row? If I do that, how will I know how many objects there are?
Here you can create an Array to store your all TimesheetRecords and push a new dynamic object when you create a new one.
// When app starts (dataFromDB is data fetched from db if any)
const TimesheetRecords = dataFromDB || []
// create a new record(mainly in a function)
const TimesheetRecord = {
id: id,
TSDate: TSDate,
TSStaffId: TSStaffId,
Hours: Hours,
Comments: Comments,
TSTaskId: TSTaskId,
Billable: Billable
}
// store to db (ajax) and then push to array
TimesheetRecords.push(TimesheetRecord)
// Check how many records are there
const count = TimesheetRecords.length
This is common pattern for storing simple objects without any behaviors(methods) in JavaScript.
Related
Trying to implement pagination using react but cannot seem to figure out a way to append the new response to an already existing state variable.
I'm trying to implement a load more functionality wherein the data is appended to the list itself.
const handleLoadMoreClick = () => {
let tempObj = postparem;
tempObj.pagenumber = tempObj.pagenumber + 1;
setPostparem(tempObj);
getProductChildMenu(APIProductList, postparem);
setCopyMenu(...copyMenu, productChildMenu);
};
Currently the map function is running iterating over productChildMenu so it replaces the data but i want to append the data in productChildMenu to copyMenu.
I tried iterating over productChildMenu and pushing each element to copyMenu but it is coming out undefined or if i push it completely at once, it creates a 2d array which does not iterate in map correctly.
You must do the following to merge 2 objects into your state.
const handleLoadMoreClick = () => {
...
...
setCopyMenu({...copyMenu, ...productChildMenu});
};
You cannot do what you are doing with tempObject here:
let tempObj = postparem;
// this is wrong.
tempObj.pagenumber = tempObj.pagenumber + 1;
setPostparem(tempObj);
Even though you call the variable tempObj a "temporary object", it is not a new object. It is just a reference to the object stored in the variable postparem.
So your code is identical to the (equally wrong) postparem.pagenumber = postparem.pagenumber + 1.
Instead, you really have to create a new object:
let tempObj = {
...postparem,
};
and then you can either modify that, or already introduce your change on object creation.
That would look like
let tempObj = {
...postparem,
pagenumber: postparem.pagenumber + 1,
};
setPostparem(tempObj);
Or even a bit shorter:
setPostparem({
...postparem,
pagenumber: postparem.pagenumber + 1,
});
This is my code. I am trying since a couple of days to create an Array of Objects, which I will then store in Local Storage. Here is the problem, I need to first Get the existing value from Local Storage.
I then need to add the new data object to the existing array. I then convert it into JSON so that I can store it back in the local storage.
onRegisterSubmit(){
const user = {
a: this.a,
b: this.b,
c: this.c,
id: Date.now()
}
var abc = [];
var get = JSON.parse(localStorage.getItem('user'));
abc = [get];
abc.push(user);
localStorage.setItem('user', JSON.stringify(abc));
console.log(JSON.stringify(abc));
console.log(get);
}
I want the JSON to be an array of objects like this,
[{"hour":1,"minute":21,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797882440"},{"hour":1,"minute":24,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797896257"},{"hour":6,"minute":14,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493815470408"}]
This is my JSON.
[[[[[[[{"id":1493820594019},{"id":1493820606448}],{"id":1493820609111}],{"id":1493820610150}],{"id":1493820610553}],{"id":1493820610827}],{"id":1493820611015}],{"id":1493820612018}]
I've been trying for several days and any help will be greatly appreciated.
The issues with that code are:
You're wrapping the result you get in an array, but in theory, you want to already have an array.
You're storing user, not get or abc. (You removed that with an edit.)
To store the array, do what you're doing:
localStorage.setItem("users", JSON.stringify(users));
To get the array:
users = JSON.parse(localStorage.getItem("users") || "[]");
Note how that provides a default (empty array) if getItem returns null because we've never stored our users there.
To add a user to the array:
users.push({id: 1, foo: "bar"});
Example (live on jsFiddle [Stack Snippets don't allow local storage]):
(function() { // Scoping function to avoid creating globals
// Loading
var users = JSON.parse(localStorage.getItem("users") || "[]");
console.log("# of users: " + users.length);
users.forEach(function(user, index) {
console.log("[" + index + "]: " + user.id);
});
// Modifying
var user = {
id: Math.floor(Math.random() * 1000000)
};
users.push(user);
console.log("Added user #" + user.id);
// Saving
localStorage.setItem("users", JSON.stringify(users));
})();
That shows you the list of current users in the console, adding one each time you refresh the page.
Try something like this:-
link https://jsfiddle.net/sureshraina/nLexkyfw/1/
var mydatas = new Array();
mydatas[0] = "data";
mydatas[1] = "data1";
mydatas[2] = "data2";
localStorage["mydatas"] = JSON.stringify(mydatas);
var datas = JSON.parse(localStorage["mydatas"]);
See this post.
You can't store Objects, you have to store a String. So the workaround is to stringify your Object before you store it (for example, you could use change it to a JSON object, store it, and read it again when needed).
I want to make a cron job that deletes deeply nested objects in my realtime database that are older than 24 hours.
I have looped through and reached the deeply nested object, but I can't grab/target the value of "addedTime" in the object. How do I grab that value so I can run .remove on the parent? So far, it comes back as undefined or it throws an error.
.schedule("every 1 hours")
.onRun(context => {
const rootDatabaseRef = admin.database().ref("ghostData/");
return rootDatabaseRef.ref.once("value").then(function(snapshot) {
console.log("snap", snapshot.val());
snapshot.forEach(function(userSnapshot) {
let buckets = userSnapshot.val().buckets;
console.log("buckets", buckets);
buckets.forEach(function(bucket) {
let currentTimeYesterday = new Date(
new Date().getTime() - 24 * 60 * 60 * 1000
).getTime();
let addedTime = bucket.val().addedTime;
console.log("curr time", currentTimeYesterday);
console.log("addedTime", addedTime);
});
});
Here is the data in my realtime database as well as the logs from the serverless cloud functions:
I think you're having problems with looping, because when you do this "buckets.forEach(function(bucket)" --> bucket in your case is the first element of the list ,
and every element has a nested dictionary , so first you have to iterate the dictionary and for each key in the dictionary , you'll get another dictionary , and you've to grab
only the added-time value.
I know it's difficult to understand but I think it's happening because you're not looping correctly.
Try the code below or something similar.
buckets.forEach(function(bucket){
let currentTimeYesterday = new ......
bucket.forEach(function(dict){
Object.keys(dict).forEach(k => {
console.log(k, ':', dict[k].addedTime);
let addedTime = dict[k].addedTime;
});
....
}
....
}
I have data being sent to a custom data list from the following code:
// Get the site name and dataLists
var site = siteService.getSite("Testing");
var dataLists = site.getContainer("dataLists");
// Check for data list existence
if (!dataLists) {
var dataLists = site.createNode("dataLists", "cm:folder");
var dataListProps = new Array(1);
dataListProps["st:componentId"] = "dataLists";
dataLists.addAspect("st:siteContainer", dataListProps);
dataLists.save();
}
// Create new data list variable
var orpList = dataLists.childByNamePath("orplist1");
// If the data list hasn't been created yet, create it
if (!orpList) {
var orpList = dataLists.createNode("orplist1","dl:dataList");
// Tells Alfresco share which type of items to create
orpList.properties["dl:dataListItemType"] = "orpdl:orpList";
orpList.save();
var orpListProps = [];
orpListProps["cm:title"] = "Opportunity Registrations: In Progress";
orpListProps["cm:description"] = "Opportunity registrations that are out for review.";
orpList.addAspect("cm:titled", orpListProps);
}
// Create new item in the data list and populate it
var opportunity = orpList.createNode(execution.getVariable("orpWorkflow_nodeName"), "orpdl:orpList");
opportunity.properties["orpdl:nodeName"] = orpWorkflow_nodeName;
opportunity.properties["orpdl:dateSubmitted"] = Date().toString();
opportunity.properties["orpdl:submissionStatus"] = "Requires Revisions";
opportunity.save();
This correctly creates data list items, however, at other steps of the workflow require these items to be updated. I have thought of the following options:
Remove the data list item and add another with the updated information
Simply update the data list item
Unfortunately I have not found adequate solutions elsewhere to either of these options. I attempted to use orpWorkflow_nodeName, which is a unique identifier generated at another step, to identify a node to find it. This does not seem to work. I am also aware that nodes have unique identifiers generated by Alfresco itself, but documentation doesn't give adequate information on how to obtain and use this.
My question:
Instead of var opportunity = orpList.createNode(), what must I use in
place of createNode() to identify an existing node so I can update its
properties?
You can use this to check existing datalist item.
var opportunity = orpList .childByNamePath(execution.getVariable("orpWorkflow_nodeName"));
// If the data list Item is not been created yet, create it
if (!opportunity ) {
var orpList = orpList .createNode(execution.getVariable("orpWorkflow_nodeName"),"dl:dataList");}
I want to store objects in jquery. The objects are 'events' each event has a date, title and some text. They need to be stored like and array (maybe thats what they will be a multi-dimensional array) so I can iterate through them with a counter.
Edit,
I like the stores var as a way to group the info but how do I add multiple items and how do I index them?
var dates = new Array('12th Dec', '14th Jan', '6th May');
var event_title = new Array('My Birthday', 'Going to Beach', 'Holiday');
var event_text = new Array('One Year Older', 'Remember the suntan lotion', 'on the plane to spain');
I need to return by index alert(dates[2], event_title[2], event_text[2]);
you can try:
var store = {};
store = {
dates : dates,
titles: titles,
infotxt: infotxt
};
Then access:
store.dates or store.title or so..
You probably don't want to store separate related info in arrays as you're doing, and then attempt to access those groups by index.
JavaScript has a perfect, native object that allows you to group similar properties. Just use an object literal:
var events = [];
events.push({
data: someData,
title: someTitle,
text: someText
});
Now you have what's referred to oftentimes as a "collection".
You could take it a step further and make each event a "class":
function MyAwesomeEvent(data, title, text) {
this.data = data;
this.title = title;
this.text = text;
}
events.push(new MyAwesomeEvent(someData, someTitle, someText));
That approach is potentially heavy-handed depending on what your specific use-case is, but it's another option.