Home > OS >  How to res convert to Like res2
How to res convert to Like res2

Time:03-23

 res = [{name:"sonu",roll:34,file:"asj.jpg", img_id:'1'},{name:"sonu",roll:34,file:"asj1.jpg", img_id:'2'},     {name:"sonu",roll:34,file:"asj2.jpg", img_id:'3'},{name:"dip",roll:67,file:"fgd3.jpg", img_id:'4'},     {name:"dip",roll:67,file:"fgd4.jpg", img_id:'5'},{name:"dip",roll:67,file:"fgd5.jpg", img_id:'6'}]

res convert to like res2

res2 = [{name:"sonu",roll:34, image: [{file:"asj.jpg",img_id:'1'},{file:"asj1.jpg", img_id:'2'},{file:"asj2.jpg", img_id:'3'}]},
{name:"dip",roll:67, image: [{file:"fgd3.jpg", img_id:'4'},{file:"fgd4.jpg", img_id:'5'},{file:"fgd5.jpg", img_id:'6'}]}]

CodePudding user response:

try this

var groupBy = function (xs, key) {
  return xs.reduce(function (rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var res0= groupBy(res, 'name');

var res2 = [];
Object.keys(res0).forEach((item) => {
  
  var newObj = { name: item, roll: res0[item][0].roll, image: [] };

  res0[item].forEach((obj) => {
    newObj.image.push({ file: obj.file, img_id: obj.img_id });
  });

  res2.push(newObj);
});

CodePudding user response:

try this

let res = [{name:"sonu",roll:34,file:"asj.jpg", img_id:'1'},{name:"sonu",roll:34,file:"asj1.jpg", img_id:'2'},     {name:"sonu",roll:34,file:"asj2.jpg", img_id:'3'},{name:"dip",roll:67,file:"fgd3.jpg", img_id:'4'},     {name:"dip",roll:67,file:"fgd4.jpg", img_id:'5'},{name:"dip",roll:67,file:"fgd5.jpg", img_id:'6'}]

var group_to_values = res.reduce(function (obj, item) {
    obj[item.name] = obj[item.name] || [];
    obj[item.name].push({file :item.file,img_id :item.img_id,roll :item.roll});
   
    return obj;
}, {});
//console.log(group_to_values)
var groups = Object.keys(group_to_values).map(function (key) {
    return {name: key,roll: group_to_values[key][0].roll, image: group_to_values[key].map(x=>({ file: x.file, img_id: x.img_id }))};
});

console.log(groups);

  • Related