1

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;
8
  • What are you trying to change? Your question in relation to the code isn't very clear. What are you trying to do with this code? The condition in your code I think should be storeState[i].name === tempLast if you are checking that the name property is equal to the tempLast value. Again, it's not very clear what the goal is here. Commented Feb 19, 2021 at 5:23
  • @DrewReese Hi, I apologize for not making it clear on my question. I have also uploaded the image to see if that can help other people to understand what I am exactly asking for. Commented Feb 19, 2021 at 5:57
  • So if the current key of the object matches the parameter, update the value associated with the key?, i.e. key = "last", update objectArray[1].last value, if key = "name" update the name property of both elements? Commented Feb 19, 2021 at 6:01
  • @DrewReese Yes, That is what I am trying to do... I know how to get the value of the key but not sure how to check if the key is equal to the key that is received from the parameter.. Commented Feb 19, 2021 at 6:05
  • @DrewReese Thank you so much! This is what I just needed. But I am looking at your code and trying to understand what you did. I really dont want to use it without understanding what that code is actually doing. Commented Feb 19, 2021 at 6:32

2 Answers 2

2

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})
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can map the previous state to new state, and when mapping each element object, check each key against a "searchKey" and if you find a match update the value.

Here's an example onHandle function that maps the objectTemp state and creates an array of object entries (i.e. array of key-value pairs) of the objects. It reduces the entries array back into an object, and while doing so checks the object keys for the match.

onHandle = (searchKey, newValue) => {
  this.setState(prevState => ({
    // map previous state to next state
    // [obj1, obj2, ...objN]
    objectTemp: prevState.objectTemp.map(obj => {
      // Create array of entries and reduce back into object
      // [[key1, value1], [key2, value2], ...[keyN, valueN]]
      return Object.entries(obj).reduce((obj, [key]) => {
        // If key is a match to search key, create new object and update value,
        // otherwise return existing object
        return key === searchKey
          ? {
            ...obj,
            [key]: newValue
          }
          : obj;
      }, obj);
    })
  }))
}

Demo

Edit how-to-change-specific-properties-on-object-array

Comments

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.