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

Time:11-02

I'm trying to generate an object which looks like this:

{
  "te-koop": [{ /*plot 1*/ }, { /*plot 1*/ }],
  "in-optie": [{ /*plot 3*/ }, { /*plot 4*/ }],
  "verkocht": [{ /*plot 5*/ }, { /*plot 6*/ }],
}

with a forEach loop. Here is my code:

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

Each status represents each key (te-koop, in-optie, verkocht) and there will be several plots that match each status. Each plot is an object.

The code snippet above is currently not working, does anybody have a suggestion?

CodePudding user response:

  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);
};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

From the above comment ...

"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."

Sophisticated guess ... a reduce based task should solve the OP's problem of generating a configuration like object of plot specific arrays ...

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

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

    plotList.push(plot);
    
    return result;

  }, {});
  • Related