gpt4 book ai didi

javascript - 如何在 jquery 或 javascript 中重构消息中显示的对象

转载 作者:行者123 更新时间:2023-12-03 07:31:46 24 4
gpt4 key购买 nike

嗨,我一直在这种情况下挣扎。也许有人可以帮助我解决这个问题。

尝试的代码:

var Obj = {
Type: {
message: "This field is required"
},
Bonus1: {
message: "This field is required"
},
Bonus2: {
message: "This field is required"
},
Bonus3: {
message: "This field is required"
},
Date: {
message: "This field is required"
},
Time: {
message: "This field is required"
}
};

var message = "";

$.each(Obj, function(i, v){
if(i.match(/Bonus/g))
{
i = i.concat(', ');
}
message += i + ": " +v.message + "\n";
});

alert(message);

如果两个或多个奖金显示此内容:

enter image description here

如果一项奖金显示此内容:

enter image description here

JS Fiddle

最佳答案

1)使用正则表达式划分键和键索引:

var re = /([^0-9]*)([0-9]*)/; // The string ends with a number
var restruct = {};

$.each(Obj, function(i, v){
var m;
var index;
if ((m = re.exec(i)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}
i = m[1];
index = m[2];
})

2) 对于每个键保存不同的消息及其对应的索引:

  if (typeof restruct[i] === 'undefined') restruct[i] = {};
if (typeof restruct[i][v.message] === 'undefined') restruct[i][v.message] = []
if (index.length>0) restruct[i][v.message].push(index)

3)构造最终消息:

 $.each(restruct, function(i) {
$.each(restruct[i], function(m,v){
message += (v.join(',') + ' ' + i).trim() + ': ' + m + '\r\n';
});
});

[https://jsfiddle.net/1b9qum1d/]

关于javascript - 如何在 jquery 或 javascript 中重构消息中显示的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35787409/

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