如何从一组数据项创建对象?

How does one create an object from an array of data items?

我正在努力从 JS 中的数组创建对象。 推入绘图对象时,我不断收到错误消息。

makeArrayFilteredPlots = () => {
  let plots = {};
  this.props.filteredPlots.forEach((plot) => {
    const status = plot.entity.status.slug;
    plots[status].push(plot);
  });
  console.log(plots);
};
  1. 在 JS 中,数组没有命名键,它只是一个列表。如果您想要命名键,请使用对象 {}
  2. plots[status] 从未被初始化。当您尝试 .push() 未定义的内容时,脚本会崩溃。在开始向其中推送内容之前将其初始化为一个空数组。

makeArrayFilteredPlots = () => {
  let plots = {};
  this.props.filteredPlots.forEach((plot) => {
    const status = plot.entity.status.slug;
    plots[status] = plots[status] || []; // Initialize an empty array
    plots[status].push(plot);
  });
  console.log(plots);
};

从上面的评论...

"The target format is not even valid JS syntax. One can not clearly see whether the OP wants to generate array items, where each item is an object with a single key (or something else). From the generating code it looks like the OP wants to create/aggregate an object where each entry (key value pair) is an array. But then we are not talking about a multi dimensional array."

复杂的猜测......一个基于reduce的任务应该解决OP生成配置的问题,例如object of plot specific 数组 ...

const plotsConfig = this
  .props
  .filteredPlots
  .reduce((result, plot) => {

    const plotKey = plot.entity.status.slug;
    const plotList = result[plotKey] ??= [];

    plotList.push(plot);
    
    return result;

  }, {});