0
var array = [{"name":"Vani","Id":"1"},{"name":"Random","Id":"1"},{"name":"Random1","Id":"2"},{"name":"Random2","Id":"2"}];

Convert to following object using reduce based on unique field value id:

var obj = {"1":[{"name":"Vani","Id":"1"},{"name":"Random","Id":"1"}],"2":[{"name":"Random1","Id":"2"},{"name":"Random2","Id":"2"}]}
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38

1 Answers1

0

You can use .reduce() method to get the desired output:

const data = [{"name":"Vani","Id":"1"},{"name":"Random","Id":"1"},{"name":"Random1","Id":"2"},{"name":"Random2","Id":"2"}];

const result = data.reduce((r, c) => {
  r[c.Id] = r[c.Id] || [];
  r[c.Id].push(c);
  return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95