How to add a new key value to react js state array?

25,620

Solution 1

I think This will meet the above scenario.

const newFile = this.state.files.map((file) => {

    return {...file, key4: val4};
});
this.setState({files: newFile });

Solution 2

You can make use of forEach and add the new value like

var newState = [...this.state.files];
newState.forEach(function(file) {
  file.key4 = "val4"
})
this.setState({files: newState}, function() {
  console.log(this.state.files);
})

Fiddle

class App extends React.Component {
  constructor() {
    super();
    this.state = {
        files: 
        [
            {
                key1: "val1",
                key2: "val2",
                key3: "val3"
            },
            {
                key1: "val1",
                key2: "val2",
                key3: "val3"
            },
            {
                key1: "val1",
                key2: "val2",
                key3: "val3"
            }
        ]
    }
  }
  componentDidMount() {
    console.log(this.state.files) ;
    
    var newState = [...this.state.files];
    newState.forEach(function(file) {
      file.key4 = "val4"
    })
    this.setState({files: newState}, function() {
      console.log(this.state.files);
    })
  }
  render() {
    return <div>Hello</div>
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Share:
25,620
ahmet
Author by

ahmet

Updated on July 27, 2022

Comments

  • ahmet
    ahmet almost 2 years

    I want to add new key value to array ınto state? I tell you what I want to do below. How can I do that? 1. Start state in consruture method

    `this.state = {
        files: []
    }'
    
    1. After I doing set state with active files

      this.setState({files: activeFiles})

    2. Screen my state

      { files: [ { key1: val1, key2: val2, key3: val3 }, { key1: val1, key2: val2, key3: val3 }, { key1: val1, key2: val2, key3: val3 } ] }

    3. How to add new key value for each file? The state I want

      { files: [ { key1: val1, key2: val2, key3: val3, key4: val4 }, { key1: val1, key2: val2, key3: val3, key4: val4 }, { key1: val1, key2: val2, key3: val3, key4: val4 } ] }

  • FabricioG
    FabricioG over 5 years
    Doesn't this mutate the state? @duwalanise
  • duwalanise
    duwalanise over 5 years
    Actually this does. I was so silly I will update this one, Thanks @FabricioG