0

how can i get all the customers with the same id in each Object into One array (unless you have a better idea) so i can get the start and end time to show in a table for that specific customer. the idea here is to show a table with fixed columns, and each row would be filled with customer name and start time for each of these columns instead of having multiple rows.

im looping over my API data in which it's returning multiple Objects with each having its own values for Example:

enter image description here

92yo
  • 518
  • 1
  • 4
  • 12
  • You could transform your results in a `Map` where the customer id is the key, and the value is an array of customers – derpirscher Feb 07 '21 at 11:01
  • 1
    Is this what you need ? https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects – Long Nguyễn Thành Feb 07 '21 at 11:11
  • Does this answer your question? [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – pilchard Feb 07 '21 at 11:15

1 Answers1

1

Better to use Object, where the key is the actual ID identifier: {ID1: [], ID2: []}- that way by just targeting the ID you get back all the data for that customer ID:

const response = [
  {customerId:"11", customerName:"John", serviceName: "foo"},
  {customerId:"88", customerName:"Anne", serviceName: "bar"},
  {customerId:"11", customerName:"John", serviceName: "baz"},
];

const customers = response.reduce((dict, data) => {
  if (!dict[data.customerId]) dict[data.customerId] = [];
  dict[data.customerId].push(data);
  return dict;
}, {});

// Get specific customer data (customerId "11"):
console.log(customers["11"]);

// Get all customers data:
console.log(customers);

This can also be done using the Map Object and its has, get and set methods:

const response = [
  {customerId:"11", customerName:"John", serviceName: "foo"},
  {customerId:"88", customerName:"Anne", serviceName: "bar"},
  {customerId:"11", customerName:"John", serviceName: "baz"},
];

const customers = response.reduce((m, {customerId:id, ...r}) => {
  if (!m.has(id)) m.set(id, []);
  return (m.get(id).push(r), m);
}, new Map());

// Get specific customer data (customerId "11"):
console.log(customers.get("11"));

// Get all customers data:
console.log([...customers]);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • But how can i check that if customer Id equals multiple for the same guy i can get all the start time and reproduce it in a table? – 92yo Feb 07 '21 at 12:09
  • See the `customers["11"]` ? It's simple as: `customers["11"].forEach(row => { console.log(row.start.dateTime); });` - that's pretty much plain data manipulation knowledge: AKA how to access values of an Object. – Roko C. Buljan Feb 07 '21 at 12:15
  • 1
    i figured it out and added couple of stuff to it to make it work. Thanks a lot for your help! – 92yo Feb 07 '21 at 15:01