Save data in array with auto Id increment

问题: 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 s...

问题:

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",
          },

回答1:

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.


回答2:

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"
}
}

回答3:

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);


回答4:

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.

  • 发表于 2019-03-19 09:56
  • 阅读 ( 88 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除