gpt4 book ai didi

javascript - 如何在javascript中保持插入顺序?

转载 作者:行者123 更新时间:2023-12-02 22:05:30 27 4
gpt4 key购买 nike

这是我的代码生成的格式:

[
    {
        "certifications": [
            {
                "certificate": "NA",
                "completed_on": "2019-09-24T18:30:00.000Z",
                "tc_name": "TC-174195"
            }
        ],
        "firstname": "Dipak",
        "lastname": "Das",
        "email": "dasdipak99@gmail.com"
    }
]

我想设计如下格式:

[
{
firstname: "Dipak",
lastname: "Das",
email: "dasdipak99@gmail.com",
certifications: [
{
certificate: "NA",
completed_on: "2019-09-24T18:30:00.000Z",
tc_name: "TC-174195"
}
]
}
]

下面是我的代码:

var user = [];
var certificate = {
certifications: []
};

certificate["firstname"] = rows[0].firstname;
certificate["lastname"] = rows[0].lastname;
certificate["email"] = rows[0].email;

for (let i = 0; i < rows.length; ++i) {
certificate.certifications.push({
certificate: rows[i].certification_names,
completed_on: rows[i].completed_on,
tc_name: rows[i].tc_name
});
}

有什么想法如何保持插入顺序吗?我对 javascript 很陌生,如果我没有解释清楚,请道歉。

最佳答案

自 ES6 以来,有人声称该顺序将是

  1. 第一个数字不断增加
  2. 按插入顺序排列的键

有这个blog post还有这个Stackoverflow thread .

但是你的台词

var certificate = {
certifications: []
};

认证作为第一个属性。所以你需要:

var certificate = {};

certificate["firstname"] = "Albert";
certificate["lastname"] = "Lee";
certificate["email"] = "a@b.com";
certificate["certifications"] = [];

certificate.certifications.push({
certificate: "Java",
completed_on: "2020/01/02",
tc_name: "java2020"
});

console.log(certificate);

为了更好地保证订单,请使用Map ,保持按键的原始插入顺序。通常你可能不需要它,但只是出于某种原因如果你想要顺序,并且可以在 for-of 循​​环中拥有这样的顺序:

var certificate = new Map();

certificate.set('firstname', "Albert");
certificate.set('lastname', "Lee");
certificate.set('email', "a@b.com");
certificate.set("certifications", []);
certificate.get("certifications").push({
"certificate": "Java",
"completed_on": "2020/01/02",
"tc_name": "java2020"
})

console.log(certificate);

for (e of certificate) console.log(e)

StackOverflow 不会打印任何内容:

console.log(certificate);

使用 Node 或 Chrome,它是:

Map {
'firstname' => 'Albert',
'lastname' => 'Lee',
'email' => 'a@b.com',
'certifications' => [
{
certificate: 'Java',
completed_on: '2020/01/02',
tc_name: 'java2010'
}
]
}

关于javascript - 如何在javascript中保持插入顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59727597/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com