Mariana Gomez-Kusnecov
Mariana Gomez-Kusnecov

Reputation: 245

How to store values from a list into an array of objects in ReactJS

I have a state that is similar to this

this.state = {
      var: "",
      arr1: [{
        pName: "",
        priority: ""
      }],
      other: ["item1", "item2", "item3"]
    }

in my render() I list out the contents of the "other" array, and next to it, a user can put any number, which would be their ranking (doesn't matter if repeated) of the items in the "other array as shown below

  <Row className="App">
    <ul>
      {this.state.other.map((item, index) =>
        <li key={index}>{item}<Input className="rankCols" type="number" id="ranking" onChange={this.handleChange.bind(this)} /></li>
        )}
    </ul>
  </Row>

What I'm trying to achieve is to store the "item" from the list and the matching "ranking" into the "arr1" so that if a user ranks item1 as "3", item2 as "1" and item3 as "2", the arr1 would be updated to be

arr1: [{
  pName: "item1",
  priority: "3"
  },
  {
  pName: "item2",
  priority: "1"
  },
  {
  pName: "item3",
  priority: "2"
  }]

The handleChange() works updating the value that the user inputs

  handleChange = event => {
    this.setState({
      [event.target.id]: event.target.value
    });
  }

I'm not sure if it can be done this way or if I'd have to use some type of loop in order to store each item along with its priority.

Upvotes: 0

Views: 2161

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

Firstly, you need to find if the items priority already exists in your array and update it if present or else add it in the array. Also you would need to provide which item you are updating to handleChange

   this.state = {
      var: "",
      arr1: [],
      other: ["item1", "item2", "item3"]
    }

  <Row className="App">
    <ul>
      {this.state.other.map((item, index) =>
        <li key={index}>{item}<Input className="rankCols" type="number" id="ranking" onChange={this.handleChange.bind(this, item)} /></li>
        )}
    </ul>
  </Row>

handleChange = (item,event) => {
    const value = event.target.value
    this.setState(prev => {
      const idx = prev.arr1.findIndex(obj => obj.pName === item)
      if(idx > -1) {
           return {
              arr1: [...prev.arr1.slice(0, idx), {pName: item, priority: value}, ...prev.arr1.slice(0, idx + 1)]
           }
      } else {
          return {
              arr1: prev.arr1.concat([{pName: item, priority: value}])
           }
      }

    }));
  }

Upvotes: 3

Related Questions