【问题标题】:Objects with same ID pushed into same array具有相同 ID 的对象被推入相同的数组
【发布时间】:2021-02-07 11:00:05
【问题描述】:

如何将每个对象中具有相同 ID 的所有客户放入一个数组中(除非您有更好的主意) 这样我就可以在表格中为该特定客户显示开始和结束时间。 这里的想法是显示一个具有固定列的表格,并且每一行将填充客户姓名和每一列的开始时间,而不是多行。

我正在循环我的 API 数据,其中它返回多个对象,每个对象都有自己的值,例如:

【问题讨论】:

标签: javascript


【解决方案1】:

最好使用 Object,其中键是实际的 ID 标识符:{ID1: [], ID2: []}- 这样只需定位 ID,您就可以取回该客户 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);

这也可以使用Map Object 及其hasgetset 方法来完成:

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]);

【讨论】:

  • 但是我如何检查客户 ID 是否等于同一个人的多个我可以获得所有开始时间并在表格中重现它?
  • 查看customers["11"] ?很简单:customers["11"].forEach(row => { console.log(row.start.dateTime); }); - 这是非常简单的数据操作知识:AKA 如何访问对象的值。
  • 我想通了,并在其中添加了一些东西以使其正常工作。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 2014-10-08
相关资源
最近更新 更多