简体   繁体   中英

How to hold index of object inside of array?

I'm trying to code "blockchain" visual implementation in React. I want to hold somehow inside array of objects(that are my blocks) index of each object. I can't figure out how to do it.

    this.state = {
      value: '',
      blocks: [{
        hash: calculateHash(1),
        timestamp: timeStamp(),
        dataOfBlock: 'Genesis Block',
        nounce: 607,
        index: 0
      }]
    }
  };

    addBlock = (event) => {
      event.preventDefault();

      this.setState({
      blocks: [...this.state.blocks, {
        hash: 'cos',
        timestamp: timeStamp(),      
        dataOfBlock: this.state.value,
        nounce: '',
        index: 1 // here's the problem
      }]
    })
    }

My code mimics what i want to accomplish where the comment is. I want to constantly add +1 to my index with each block.

You can use length as index of new object when adding new object
Note : this.state.blocks.length will the next index because index start from 0

blocks: [...this.state.blocks, {
        hash: 'cos',
        timestamp: timeStamp(),      
        dataOfBlock: this.state.value,
        nounce: '',
        index: this.state.blocks.length
      }]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM