javascript 为对象内的数组指定连续数字

bzzcjhmw  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(76)

我正在创建一个应用程序,其中用户从客户端输入数据。此数据将存储在localStorage。在此之前,一切正常。但我需要计算对象的length,然后在创建和保存时自动为每个客户端分配一个连续的数字。例如,由于javascript对象从0开始编号,第一个客户端在array上是0,但在真实的生活中它是1。所以,我需要迭代并获得最后一个客户端,因为js命令它,然后添加1,然后将其分配给clientn以存储在此客户端数据上。

Json

Clients:"[{
    "id":"qece2345-cd9d-4898-fd18-3ded710a8062",
    "hasPic":false,
    "picId":2,
    "picSrc":"",
    "picFile":[],
    "createdOn":"2023-03-30T14:22:22.899Z",
    "firstName":"JND PLUS MASTER",
    "job":"Destroza avernos",
    "clientn":""
    }]"

一米七三

function setClientNumber() {
    var clients = JSON.parse(localStorage.getItem("Clients")) || {};
    for (var m = 0; m < clients.length; m++) {
        clientNumber = clients.slice(-1)["0"].clientn;
        clients.push(client, clientNumber + '1');
        localStorage.setItem("Clients", JSON.stringify(clients));
}

预期成果

Clients:"[{
    "id":"qece2345-cd9d-4898-fd18-3ded710a8062",
    "hasPic":false,
    "picId":2,
    "picSrc":"",
    "picFile":[],
    "createdOn":"2023-03-30T14:22:22.899Z",
    "firstName":"JND PLUS MASTER",
    "job":"Destroza avernos",
    "clientn":"1"
    },{
    "id":"qece2345-cd9d-4898-fd18-3ded710a8062",
    "hasPic":false,
    "picId":2,
    "picSrc":"",
    "picFile":[],
    "createdOn":"2023-03-30T14:22:22.899Z",
    "firstName":"JND PLUS MASTER",
    "job":"Destroza avernos",
    "clientn":"2"
    },{
    "id":"qece2345-cd9d-4898-fd18-3ded710a8062",
    "hasPic":false,
    "picId":2,
    "picSrc":"",
    "picFile":[],
    "createdOn":"2023-03-30T14:22:22.899Z",
    "firstName":"JND PLUS MASTER",
    "job":"Destroza avernos",
    "clientn":"3"
    }]"

注意,第一个客户端object 0具有"clientn":1;object 1,具有"clientn":2;object 2,有"clientn":3

xmakbtuz

xmakbtuz1#

在您的push中,由于某种原因推送了两个项目

尝试更简单的东西,例如.map

function runSetClientNumber() {
    const oldClients = JSON.parse(localStorage.getItem("Clients")) || {};
    const newClients = oldClients.map(
        (oldClient,zeroBasedIndex)=> ({
            ...oldClient,
            clientn: 1+zeroBasedIndex
        })
    );
    localStorage.setItem("Clients", JSON.stringify(newClients));
}

相关问题