Reputation: 3416
I have an array of objects:
const boxOptions = [
{ 0: "$250", 1: "$500", 2: "$750", 3: "$1000", 4: "$1250", 5: "$1500" },
{ 0: "$500", 1: "$750", 2: "$1000", 3: "$1250", 4: "$1500", 5: "$2000" },
{ 0: "$750", 1: "$1000", 2: "$1250", 3: "$1500", 4: "$2000", 5: "$2500" },
]
Which is set to the state and then rendered in my RangeSlider component:
state = {
boxOptions: boxOptions,
tier: 0
};
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<RangeSlider label='What sort of box are you after?' onChange={this.handleBoxChange} min={0} max={5} defaultValue={this.state.boxIndex} marks={this.state.boxOptions[this.state.tier]} step={null} />
</div>
);
}
When I try to get the length of it on my onChange handler, I get undefined:
handleBoxChange = index => {
console.log(this.state.boxOptions[this.state.tier].length, 'boxOptions')
}
Why is this?
Upvotes: 0
Views: 8499
Reputation: 2152
this.state.boxOptions[this.state.tier].length
this.state.boxOptions[this.state.tier]
will work and return { 0: "$250", 1: "$500", 2: "$750", 3: "$1000", 4: "$1250", 5: "$1500" }
however, Object doesn't have the property .length
and this is why it returns undefined.
If you wanted the total number of properties on this object, you can use:
Object.keys(this.state.boxOptions[this.state.tier]).length
Object.keys(object)
will return you an array of all the keys within an Object
Upvotes: 3