Skip to content

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

I’m struggling to create an object from an array in JS. I keep getting an error when pushing into the plots object.

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

Answer

  1. In JS, an array has no named keys, it’s only a list of things. If you want named keys, use an object {}
  2. plots[status] is never initialized. When you try to .push() stuff in something undefined, the script crashes. Initialize it to an empty array before starting to push things in it.

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