简体   繁体   中英

How to restructure an object show in message in jquery or in javascript

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:

在此处输入图片说明

JS Fiddle

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';
     });
 });

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM