Hi SO i've been struggling in this kind of situation. Maybe someone who can help me in this problem.
Attempted Code:
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);
If two or more Bonus show this:
If One Bonus show this:
1) Divide the key and key index using regular expressions:
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) For each key save differing messages and their corresponding indexes:
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) Construct the final message:
$.each(restruct, function(i) {
$.each(restruct[i], function(m,v){
message += (v.join(',') + ' ' + i).trim() + ': ' + m + '\r\n';
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.