我已经有以下格式:

[
   {
      user_id:"UID20",
      first_name:"Vasanthis",
      email:"[email protected]"
   },
   {
      user_id:"UID19",
      first_name:"Murali",
      email:"[email protected]"
   }
];


我需要像下面的格式进行转换:

[
   {
      "user_id":[
         "UID20",
         "UID19"
      ],
      "first_name":[
         "Vasanthis",
         "Murali"
      ],
      "email":[
         "[email protected]",
         "[email protected]"
      ]
   }
]

最佳答案

您可以创建一个遍历数组的函数,并提取属性名称和值,然后将它们放入新的对象中,如下所示:

function arrObjToObjArr(a){
  var newObj = {};

  $.each(a, function(k,v) {
    $.each(v, function(prop, val) {
      (newObj[prop] == undefined) ? newObj[prop] = [val] : newObj[prop].push(val);
    });
  });
  return newObj;
}


参见此工作提琴:https://jsfiddle.net/o56pmk38/

关于jquery - JSON格式转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48664386/

10-10 22:00