I’m struggling to create an object from an array in JS. I keep getting an error when pushing into the plots object.
JavaScript
x
9
1
makeArrayFilteredPlots = () => {
2
let plots = {};
3
this.props.filteredPlots.forEach((plot) => {
4
const status = plot.entity.status.slug;
5
plots[status].push(plot);
6
});
7
console.log(plots);
8
};
9
Advertisement
Answer
- In JS, an array has no named keys, it’s only a list of things. If you want named keys, use an object
{}
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.
JavaScript
1
9
1
makeArrayFilteredPlots = () => {
2
let plots = {};
3
this.props.filteredPlots.forEach((plot) => {
4
const status = plot.entity.status.slug;
5
plots[status] = plots[status] || []; // Initialize an empty array
6
plots[status].push(plot);
7
});
8
console.log(plots);
9
};