gpt4 book ai didi

javascript - 如何使用可用于对象元素的最低可能序列更新数组中的对象元素?

转载 作者:搜寻专家 更新时间:2023-10-30 21:33:31 26 4
gpt4 key购买 nike

我正在验证和更新对象数组中具有最低可用序列号的对象的名称属性。

    var instances = [
{
"Name": "Packer-Builder-01",
"InstanceId": "i-03802c9af5ca28c15"
},
{
"Name": "Packer-Builder",
"InstanceId": "i-03802c9af5ca25z17"
},
{
"Name": "Packer-Builder",
"InstanceId": "i-03802c9af5ca38l21"
},
{
"Name": "Packer-Builder-03",
"InstanceId": "i-0f9c76032682211e8"
}
]

应该是;

 instances =   [
{
"Name": "Packer-Builder-01",
"InstanceId": "i-03802c9af5ca28c15"
},
{
"Name": "Packer-Builder-02",
"InstanceId": "i-03802c9af5ca25z17"
},
{
"Name": "Packer-Builder-04",
"InstanceId": "i-03802c9af5ca38l21"
},
{
"Name": "Packer-Builder-03",
"InstanceId": "i-0f9c76032682211e8"
}
]

我的做法是从对象数组创建两个数组,然后使用 for each 循环比较它们。解决方案有效,但我觉得这个要求的代码太多了。请提出一些方法?

最佳答案

您可以在 Set 中收集所有使用过的号码并为编号取一个新的未使用值。

var instances = [{ Name: "Packer-Builder-01", InstanceId: "i-03802c9af5ca28c15" }, { Name: "Packer-Builder", InstanceId: "i-03802c9af5ca25z17" }, { Name: "Packer-Builder", InstanceId: "i-03802c9af5ca38l21" }, { Name: "Packer-Builder-03", InstanceId: "i-0f9c76032682211e8" }],
values = new Set(instances.map(({ Name }) => +Name.match(/\d{2}$/)));

instances.forEach((i => o => {
if (/\d{2}$/.test(o.Name)) return;
while (values.has(i)) i++;
o.Name += '-' + i.toString().padStart(2, '0');
i++;
})(1));

console.log(instances);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何使用可用于对象元素的最低可能序列更新数组中的对象元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55676717/

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