0

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?

Link to Sandbox

2
  • this.state.boxOptions[this.state.tier] is an object, not an array. Did you mean this.state.boxOptions.length? Commented Apr 18, 2019 at 23:11
  • your sandbox link doest work , Not sure if only for me. Commented Apr 18, 2019 at 23:13

1 Answer 1

3
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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'm AFK atm but will confirm it works shortly and then accept as accepted answer when it allows me. Edit: just what I needed. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.