Reputation: 141
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",
},
Upvotes: 1
Views: 4021
Reputation: 1443
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);
}
Upvotes: 2
Reputation: 736
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.
Upvotes: 2
Reputation: 1267
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);
Upvotes: 2
Reputation: 73
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"
}
}
Upvotes: 2