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