简体   繁体   English

使用自动 Id 增量将数据保存在数组中

[英]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.我有一个以下格式的数组,但在表单提交时,没有可用的“ID”字段。 I want that when the form is submitted by the user then an auto-generated ID should be given and save in JSON Array.我希望当用户提交表单时,应该给出一个自动生成的 ID 并保存在 JSON 数组中。 On each form submit method, it should check if ID is given already or not.在每个表单提交方法上,它应该检查是否已经给出了 ID。 If does not then do assign.如果没有,则分配。

private list :any;
 this.list = {
      "a_Rows": [
        {
          "id": "1",
          "sname": "amir",
          "sType": "Cheque",
          "semail": "ert",
          },

Write a function that generates random ids ensures the id field in JSON contains a value when a form submits.编写一个生成随机 id 的函数,确保 JSON 中的 id 字段在表单提交时包含一个值。 If the id field needs to be unique, a fetch of all ids is required to check for uniqueness.如果 id 字段需要唯一,则需要获取所有 id 以检查唯一性。

You could either use a uuid for your ids, which are guaranteed to be unique.您可以为您的 id 使用uuid ,它保证是唯一的。 Or (eg 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.或者(例如,如果您的 id 需要是整数)只需有一个全局计数器,您会随着每次提交而增加该计数器,并将其用作新元素的 id。

Example:例子:

items = [];
idCounter = 0;
function addItem(item) {
    item.id = idCounter++;
    items.push(item);
}

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.请看下面的这个例子,我创建了一个你需要的函数,它将创建唯一的 id 并添加到 json 对象中,并带有所有相应的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM