gpt4 book ai didi

javascript - 如何更改 key 号码?

转载 作者:行者123 更新时间:2023-11-29 19:10:34 26 4
gpt4 key购买 nike

我有这个对象:

a = {"formData": {
"total": "60.00",
"tr0_RTN": "PZH",
"tr0_amount": "10.00",
"tr2_RTN": "SUB",
"tr2_amount": "30.00",
"tr7_RTN": "KFC",
"tr7_amount": "20.00",
}};

如何将键序列更改为:

a = {"formData": {
"total": "60.00",
"tr0_RTN": "PZH",
"tr0_amount": "10.00",
"tr1_RTN": "SUB",
"tr1_amount": "30.00",
"tr2_RTN": "KFC",
"tr2_amount": "20.00",
}};

我可以用 native 或 lodash 做到这一点吗?

最佳答案

您可以获得所有相关 key ,查找零件并构建新的连续数字。

然后将旧值分配给新属性并删除旧键。

 old key       new key                      action
---------- ---------- --------------------------------------------
tr0_RTN tr0_RTN no, because old key and new key are the same
tr0_amount tr0_amount same as above
tr2_RTN tr1_RTN create new key, delete old key
tr2_amount tr1_amount same
tr7_RTN tr2_RTN same
tr7_amount tr2_amount same

var a = { "formData": { "total": "60.00", "tr0_RTN": "PZH", "tr0_amount": "10.00", "tr2_RTN": "SUB", "tr2_amount": "30.00", "tr7_RTN": "KFC", "tr7_amount": "20.00", } };

Object.keys(a.formData).filter(function (k) {
return k.indexOf('tr') === 0;
}).sort(function (a, b) {
return a.match(/\d+/) - b.match(/\d+/);
}).forEach(function (k) {
var m = k.match(/(\d+)_(.*)/),
kk;
if (m[1] !== this.last) {
this.counter++;
this.last = m[1];
}
kk = 'tr' + this.counter + '_' + m[2];
if (k !== kk) {
a.formData[kk] = a.formData[k];
delete a.formData[k];
}
}, { counter: -1, last: '' });

console.log(a);

关于javascript - 如何更改 key 号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39182935/

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