Save data in array with auto Id increment - javascript

I have an array in the following format but on form submit, there is no "ID" field available. I want that when the form is submitted by the user then an auto-generated ID should be given and save in JSON Array. On each form submit method, it should check if ID is given already or not. If does not then do assign.
private list :any;
this.list = {
"a_Rows": [
{
"id": "1",
"sname": "amir",
"sType": "Cheque",
"semail": "ert",
},

You could use the below code
<button onclick="submit()">Submit</button>
submit() {
let s = (new Date()).getTime().toString(16) + Math.random().toString(16).substring(2) + "0".repeat(16);
let uuid = s.substr(0,8) + '-' + s.substr(8,4) + '-4000-8' + s.substr(12,3) + '-' + s.substr(15,12);
let data = {
id : uuid,
sname: "amir",
sType: "Cheque",
semail: "ert"
}
}

Please look at this example below, i have create a function as such
u need, it will create unique id and add into the json object with all
of it corresponding value.
let value = { 2071 : {id :101, name: "bathri" , age:22}}
let idIndex;
function CreateJson(name, age){
this.id = generateNewId();
this.name = name;
this.age = age;
return value[this.id] = this;
}
function generateNewId(){
idIndex = Math.floor(Math.random() * 9999) + 1;
if(Object.keys(value).includes(idIndex) == idIndex){
idIndex = generateNewId()
}
return idIndex;
}
let result = new CreateJson('nathan','23')
console.log(value);

Write a function that generates random ids ensures the id field in JSON contains a value when a form submits. If the id field needs to be unique, a fetch of all ids is required to check for uniqueness.

You could either use a uuid for your ids, which are guaranteed to be unique. Or (e.g. if your ids need to be integers) just have a global counter which you increase with each submit and use that as id for new elements.
Example:
items = [];
idCounter = 0;
function addItem(item) {
item.id = idCounter++;
items.push(item);
}

Related

Can't send data to a php script via $.post()

I'm implementing a cart on my website. It works this way: On catalog page there's four products and each has its own "Add to cart" button. Every button has its own onClick attribute which is set to addToCart() function in mu JS file. User can click on the button, and when he does so, js script is initiated. It writes product's id and increase its amount in the sessionStorage in foramt like this: "1=1", or "5=2" where the frist number is index, i.e. product's id, and second one is amount of the product.
And the next thing that I got to do is transfer info about product id and its amount to the PHP's session. And for this purpose I'm using jQuery function post(). But it doesn't work for some reason
add_to_cart.js:
function addToCart(event) {
const PRODUCT_ON_PAGE = 4;
event = event || window.event;
const productId = Number(event.currentTarget.id);
const pageId = Number(document.querySelector(".page-num-highlight").textContent);
let index = Number((pageId - 1) * PRODUCT_ON_PAGE + productId);
let item;
const parseSign = "=";
let quantity = "";
item = sessionStorage.getItem(index);
if (item) {
for (let i = 0; i < item.length; i++) {
if (item[i] == parseSign) {
for (let j = i + 1; j < item.length; j++)
quantity += item[j];
quantity = Number(quantity);
quantity++;
quantity = String(quantity);
item = index + "=" + quantity;
sessionStorage.setItem(index, item);
}
}
}
else {
sessionStorage.setItem(index, String(index) + "=1");
}
$(() => {
let productIndex = index;
let productValue = quantity;
$.post("updateSession.php", {
index: productIndex,
value: productValue
});
})
}
As you can see I process the corresponding index and value of product on which addToCart() was triggered. Index of the product is index variable, amount of product is quantity variable.
And the next step is to send index and quantity variables to php processing script called updateSession.php in order to create/update info of product in PHP's session.
updateSession.php:
<?php
if (isset($_POST["index"]) && isset($_POST["value"])) {
$index = $_POST["index"];
$value = $_POST["value"];
$_SESSION[$index] = $value;
}
UPD1 jQuery part (unwrapped):
let productIndex = index;
let productValue = quantity;
$.post("updateSession.php", {
index: productIndex,
value: productValue
});
UPD2:
**What is not working**: when I go to cart.php var_dump() says that $_SESSION array is empty(). And I don't know where is problem: in add_to_cart.js jQuery part or in updateSession.php
UPD3:
In my console log there's two errors when addToCart() is initiated by clicking "Add to cart" button.
These 2 errors say that post() is not a function. First says jQuery.Deferred exception and second says Uncaught TypeError
Using id of object as key in JS is not a really good practice because JS reaffect key to not have lost indexes. Prefer to use full object with id key setted to your id object.
<button onclick="addToCart(6)">Add to cart</button>
In your HTML button, pass productId as element, it will be easier to use
function addToCart(productId) {
// Search if your object is already in your cart
let cartProductIndex = yourCart.map(p=>p.id).indexOf(productId)
if (cartProductIndex !== -1) { // If you have found it
cart[cartProductIndex].quantity++;
} else { // If you have not found it
// Construct your object like this
let newProduct = {
id: productId,
quantity: 1
}
// Then add it to your cart
cart.push(newProduct)
}
}
// Your cart will looks like this :
[
{
id: 3,
quantity: 1
},
{
id: 6,
quantity: 12
}
]
// Finally, you can send your post request
let datas = {
cart: cart
}
$.post("updateSession.php", datas)
// Your php file
$data = json_decode($_POST['cart']);
So your $data variable will looks like this :
$data = [
[
"id" => 3,
"quantity" => 1
],
[
"id" => 6,
"quantity" => 12
]
];

How to replace words in a sentence with its values in javascript?

I have the following scenerio , where I have the following string
Edit: const message = results.doc.data().taskSettings.taskInProgressSettings.pushNotifications.onAssignmentNotifyEmployee.message;
I get the message from db , and the variables are not necessarily taskId , customerName . It can be taskId , customerName , customerId, taskCreaterName , employeeName , employeeId. The message may contain any of the above variables and i need to replace them in run time with its values.
message:`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`
let taskId = T-100;
let taskCreaterName = 'mark';
let customerName = 'henry';
and I want to replace the variables (taskId , taskCreaterName , customername) with its values and the final result should be the following,
newMessage = Task T-100 assigned by mark for customer henry
What would be the best way of achieving this. Thanks
To make this work in generic way you can keep 1 object (like 'withData' I created below, rather than maintaining different variables) to store values to replace and let generic function (replace) take care of all the changes like below
let message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}'
let withData = {
taskId: 'T-100'
, taskCreaterName: 'mark'
, customerName: 'henry'
}
function replace(obj, withData) {
let result = message.slice(0)
for (let [key, value] of Object.entries(withData)) {
result = result.replace('${' + key + '}', value)
}
return result
}
let result = replace(message, withData)
console.log(result)
// In case Object.entries is not supported
function replace(obj, withData) {
let result = message.slice(0)
for (let key in withData) {
let value = withData[key]
result = result.replace('${' + key + '}', value)
}
return result
}
You can store values with target names in object and use .replace() to replacing target part of string with values in object. If value with matched name exist in object replace it with value.
var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName} and ${newVar}';
var values = {
taskId: 'T-100',
taskCreaterName: 'mark',
customerName: 'henry'
};
var newStr = message.replace(/\$\{(\w+)\}/g, function(match, cont){
return typeof values[cont] !== 'undefined' ? values[cont] : match;
})
console.log(newStr);
You don't need to do anything. Js will replace the variables with value at runtime.
This is probably the simplest way to accomplish the thing you're looking for:
let taskId = 'T-100';
let taskCreaterName = 'mark';
let customerName = 'henry';
let newMessage = 'Task ' + taskId + ' assigned by ' + taskCreaterName + ' for customer ' + customerName;
Where newMessage has "Task T-100 assigned by mark for customer henry".
Depending on the value of T in your code, which you did not provide, I will assume it holds a valid Integer number.
let T = parseInt(Math.random() * 1000);
let taskId = T-100;
let taskCreaterName = 'mark';
let customerName = 'henry';
//assuming T-100 is a result of an expression, you would do something like:
console.log(`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`);
//assming T-100 is a litral string, then you don't need to parse it at all
console.log(`Task T-100 assigned by ${taskCreaterName} for customer ${customerName}`);
You could use String#replace with custom callback and eval (name contains only chars [a-zA-z0-9] so it should be safe)
var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}';
let taskId = 'T-100';
let taskCreaterName = 'mark';
let customerName = 'henry';
var newMessage = message.replace(/\${([\w]+)}/g, function(match, name){
return eval(name);
})
console.log(newMessage);

Different names for different objects of same type

I have an array of objects which are all the type 'person' but I would like the array to contain maybe something like 'person0', 'person1', etc. I currently have this:
var population = [];
var populationCount = 0;
function person(id,age){
//simplified version
this.id = id;
this.age = age;
}
function createPerson(){
population[populationCount] = new person();
population[populationCount].id = populationCount;
population[populationCount].age = 0;
populationCount ++;
}
for(var i = 0; i < 10; i++){
createPerson();
}
The array currently contains "person, person, person, ..." but I would like it to contain "person0, person1, person2, ...".
Why I think this would be useful ...
if let's say population[100] would die, that would be the person with the id of 100, population[101] would take its place, assuming I just simply use population.splice[100] when he dies. So now population[100] has the id 101 and now it would be useful if the array of population would contain different 'names' so you could use indexOf to get the index of any specific person ...
You are confusing a type with an identifier.
Each instance that you make is an instance of a person, that's not going to change. Object types are object types - - person[6] is still an instance of a person.
The id property or an index would be the best approaches to differentiate one instance of person from the next.
Also, your structure is a bit off here. person is a constructor function that takes two arguments, but you don't pass those arguments when you construct a person. Instead you are setting them as properties, which is OK, but counter-intuitive to the way your code is written. And, your createPerson function should decouple the creation of the person from the addition of it to the array.
This structure would be a better approach:
var population = [];
var populationCount = 0;
// By convention, constructor funcitons should be Pascal-Case
function Person(id,age){
//simplified version
this.id = id;
this.age = age;
}
function createPerson(){
// To make this function more true to its name, just have it return
// a new Person. It shouldn't be this funciton's job to know where
// or how that Person is going to be used.
// Also, just pass the arguments that the function is expecting
return new Person(++populationCount, 0);
}
for(var i = 0; i < 10; i++){
// Here, you have a plan for how to use the Person, so here is where
// you should add it to the array. By decoupling the addition of the
// Person to the array from the creation of the Person, the "createPerson"
// function becomes more useful.
population[populationCount] = createPerson();
}
console.log("The population consists of: ", population);
console.log("The last person in the population is: ", population[population.length - 1]);
console.log("The third person in the population is a: ", population[2].constructor.name);
console.log("The third person in the population has an id of: " + population[2].id);
If you are concerned about indexes not matching ids, you could always create a "reset" function, like this:
var population = [];
var populationCount = 0;
function Person(id,age){
this.id = id;
this.age = age;
}
function createPerson(){
return new Person(++populationCount, 0);
}
for(var i = 0; i < 10; i++){
population[populationCount] = createPerson();
}
// Now, kill off the first 5 people:
population.splice(0,5);
console.log("First 5 people are gone. Array now contains: " + population.length + " people.");
console.log("First person's id is: " + population[0].id);
// *****************************************************************************
// Create a new array with the old members, but update the ids
var newPopulation = [];
function rePopulate(ary){
newPopulation = ary.map(function(element){
element.id = newPopulation.length + 1;
return element;
});
}
rePopulate(population);
console.log("The array has been recreated and ids have been adjusted");
console.log("First person's id is now: " + newPopulation[0].id);
And, if you want to be able to find a Person in the array based on the id without knowing what the corresponding index is, you can do this:
var population = [];
var populationCount = 0;
function Person(id,age){
this.id = id;
this.age = age;
}
function createPerson(){
return new Person(++populationCount, 0);
}
for(var i = 0; i < 10; i++){
population[populationCount] = createPerson();
}
// Now, kill off the first 5 people:
population.splice(0,5);
console.log("First 5 people are gone. Array now contains: " + population.length + " people (id's 6 - 10).");
console.log("First person's id is: " + population[0].id);
// *****************************************************************************
// With a simple "find" function, you can locate the correct person based on
// their id and you don't have to worry about the index at all.
function findPerson(id) {
return population.find(function(p){
return p.id === id;
});
}
var x = 7; // Whatever id you are looking for
console.log("Person with id of 7 is: ", findPerson(x));
By saying you would like to have person0, person1, person2, ... You are saying you want infinite number of different types, not just different objects. I do not know of a way to dynamically create types. As said in the comments, you would have to key-value pairs. Why not give each person a unique identifier, which I believe you are already doing.
You could have those objects nested within an object, say:
var persons = [
{
person0:
{
id: 0,
age: 69,
name: 'john doe'
},
person1:
{
...
},
...
}
]

How to retrieve string stored inside a variable?

I have a variable params inside a function someFunction(),
function someFunction() {
var params = ""
params += "type=" + type + "&intro=" + intro + "&val=" + val; // then I add a value on params
console.log(params.val); // now, how can i do this?
}
Any ideas?
Better to write your custom function.
Here what I have tried.
window.onload = function() {
var params = "";
var type = "types";
var intro = "int";
var val = "values";
params += "type=" + type + "&intro=" + intro + "&val=" + val;
var convertToObject = function(strParams) {
var objQueryString = {};
var arrParam = strParams.split('&');
console.log(arrParam)
arrParam.forEach(function(value, key) {
var arrKyValue = value.split('=');
objQueryString[arrKyValue[0]] = arrKyValue[1];
})
return objQueryString;
}
objParams = convertToObject(params);
console.log(objParams.val, objParams["val"])
}
Here is Plunker
When it's a string, it's a string. You could parse it to get values based on known format, but there is no way of referencing something inside of the string.
Therefore, it's better to store params in the object for later use and create a string only when you need it, based on that object.
So, it could be like this:
var params = {
val: val,
type: type,
intro: intro
};
then, params.val will be accessible. When you'll need a string, you'd do var string = "type=" + params.type + "&intro=" + params.intro + "&val=" + params.val;
Your params variable is just a string. What you are trying to do is access it like an object.
A better solution would be:
// Create an object
var params = {};
// Create the properties
params.type = "some type";
params.val = "some value";
params.intro = "some intro";
// Alternatively
var params = {
type: "some type",
val: "some value",
intro: "some intro"
};
// Function that does something with your params
function doSomething(input) {
console.log(input.val);
}
// Function that converts your object to a query string
function toQueryString(input) {
var keyValuePairs = [];
for (var key in input) {
if (input.hasOwnProperty(key)) {
keyValuePairs.push(encodeURI(key) + "=" + encodeURI(input[key]));
}
}
return keyValuePairs.join("&");
}
doSomething(params);
console.log(toQueryString(params));
Outputs
some value
type=some%20type&val=some%20value&intro=some%20intro
As a side note, it is generally a bad idea to use words that can be potentially a keyword in your code or in the future (IE: params). A better name would be one that is informative, such as welcomeMessage, introduction or employee (Based off the 3 values you listed)
var params = "" is not a function, its a statement. A function in JS is created by using function(params) = {} or in ES6 you can use =>. When you use += on a sting you are saying "take whatever string is already in params and add on to it what Im about to tell you." After your statement is evaluated you have a new string. Although strings can be accessed like arrays e.g. x = 'hello' and then x[0] would return 'h' where 0 refers to the character at the index of the string. You are trying to use dot notation which is used for JS object literals e.g. x = {prop1: 200, prop2: 300} then x.prop1 would return 200. Or using the array syntax you would do x[prop1] instead.
Do it this way, check demo - fiddle:
var value = false, temp;
params.split('&').forEach( function(item) {
temp = item.split('=');
if(temp[0] === 'val') {
value = temp[1];
}
})
console.log(value);

jQuery.data only saves data from the last Element

i am trying to use jQuery.data() and save an Object to my HTML-Elements. Everytime i add an list-Element to my unordered List it only saves the last object to the specific li-Element. Every other li-Elements saved data gets thrown away!
I've built a little Example. JSBin-Example
On the left, i create a List with an Object saved to it. On the right i am trying to show the data related to the Object.
Why does it only show the Object related to the last HTML-Element?
Working example:
JSBin-Example
That's because you are modifying innerHTML property of the wrapper element. What happens is in each iteration the elements are regenerated, the current elements are removed and the new elements don't have any stored data. Using innerHTML property is the worst way of modifying element contents. You just need to create a li element and append it to the wrapper element:
var random = 0;
// var testObject = [];
function addNewItem(){
random += 1;
var id = "testId" + random;
var text = "This is my " + random + ". text";
var data = {id: id, text: text};
// testObject.push(data);
// You can pass an object as the second argument
// to jQuery constructor and it calls the
// corresponding methods as setter
$('<li></li>', {
text: text + JSON.stringify(data),
id: id,
data: data
}).appendTo('#listId');
}
// bind and trigger click event
$("#add").on('click', addNewItem).click();
I changed
for(var i = 0; i < testObject.length; i++){
var listItem = "";
var id = testObject[i].id;
listItem += liStart + id + liStart2;
listItem += testObject[i].text;
listItem += liEnd;
unorderedList.innerHTML += listItem;
$("#"+id).data(testObject[i]);
}
to this in your updatelist function
//for(var i = 0; i < testObject.length; i++){
var id = testObject[testObject.length-1].id;
listItems += liStart + id+"savedData" + liStart2;
listItems += JSON.stringify($("#"+id).data());
listItems += liEnd;
//}
savedData.innerHTML += listItems;
and it fixed the issue
To help you understand my comment on the question I thought it best I'd give an example of what I meant.
I didn't have enough time to fully go through the solution but wanted to give an example of what I'd call more readable code.
I've added all variables at the top of the function. This will allow you to read and find items much quicker if you needed to alter them.
I've also merged a lot of the string values that you had into an object, namely the li element.
I've never used $.data() as an object before so wasn't really aware how I could use it to set the values in the updateSavedData() $('li'), although the console.log() does show the correct key / values.
$(document).ready(function(){
var uID = 0;
var testObject = [];
var unorderedList = $("#listId");
var savedList = $("#savedData");
var TOL = 0; //TestObjectLength
var textTemplate = "This is my [0] text!";
function addNewItem(){
uID++;
testObject.push({id: uID, text: textTemplate.replace("[0]", uID)});
TOL = testObject.length-1;
updateList();
}
function updateList(){
var li = $('<li>', { id: testObject[TOL].id, data: testObject[TOL], text: testObject[TOL].text });
li.appendTo(unorderedList);
updateSavedData(li.data());
}
function updateSavedData(li){
console.log(JSON.stringify(li));
$('<li>', JSON.stringify(li)).appendTo(savedList);
}
addNewItem();
$("#add").on('click', addNewItem);
});
Working Example
http://jsbin.com/ralizazahe/1/edit?js,console,output
Anyone that wants to progress on that please do as I'd also like to see how this could be progressed more.
Update
Taken it a step more and refactored to this
$(document).ready(function(){
var $displayList = $("#listId");
var $savedList = $("#savedData");
var textTemplate = "This is my {0} text!";
var uID = 0; //Unique ID
var data = { id: null, text: null }; //Gives a reference
function init(){
uID++;
data = { id: uID, text: textTemplate.replace("{0}", uID) };
}
function addNewItem(){
init();
$('<li>', data).appendTo($displayList);
updateSavedData(data);
}
function updateSavedData(li){
$('<li>', li).appendTo($savedList);
}
addNewItem();
$("#add").on('click', addNewItem);
});
http://jsbin.com/bajekagoli/1/edit?js,console,output

Categories

Resources