How to change specific properties on object array?

enter image description hereI have question about changing properties inside the object array. I will post my code below for better understanding. First, I have object array that contains two array and first array contain attribute called "first" and second array contains "last". When I click on the function it will pass the specific name such as first or last as string. After that I have to loop through the object array and change the value that matches the properties name (tempFirst,tempLast). I just declared inside the onHandle function but on my real project, I am passing through the parameters.

example would be: if (first === first) change the value of that property.

import logo from './logo.svg';
import './App.css';
import react ,{ Component } from 'react';


class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      objectTemp: []
    };
  }

  componentDidMount(){
    let objectArray = [
      {
        name: "hello",
        first: 77
      },
      {
        name: "world",
        last: 66
      },
    ]

    this.setState({
      objectTemp: objectArray
    })
  }

  onHandle = () => {
    let tempFirst = "first";
    let tempLast = "last";

    let storeState = [...this.state.objectTemp];
    //console.log(storeState);
    
// here i want to check if either tempfirst or templast is equal to the property on object array
    for(let i = 0; i < storeState.length; i++){
      //if(storeState[i] === tempLast){
        console.log(...storeState[i]);
      //}
    }
  }

  render() {
    console.log(this.state);
    return <button onClick={this.onHandle}>VIEW</button>;
  }
}

export default App;

12 thoughts on “How to change specific properties on object array?”

  1. I think the step for your modification is:

    onHandle = (firstName: string, value: any) => {
        /// Modify your data:
        const newData = this.state.objectTemp.map( item => {
             /// Update Data if matched condition
             if(item.firstName === firstName){
                 item.value = value
             }
             return item
        })
    
        /// Update state
        this.setState({objectTemp: newData})
    }
    
    Reply

Leave a Comment