Home > Software engineering >  How to update specific object value of an array in javascript
How to update specific object value of an array in javascript

Time:10-16

I have an array of objects, I did a map on that array now I want to change specific object values. I used onChange method inside map() function. It not working properly could someone please help me to achieve this problem solution.

thanks

localPreRoutingCall &&
    localPreRoutingCall.map((item, index) => (
      <>
        <div className="pre-route-title">{item && item.field_title}</div>
        <textarea
          placeholder="Enter something"
          className="pre-route-textarea"
          value={item && item.value}
          onChange={(e) => {
            e.persist();
            changeObjectValue(e.target.value, item);
          }}
        />
        <div className="pre-route-description">
          {item && item.description}
        </div>
      </>
    ))

A function where I am updating object value

 const changeObjectValue = (value, item) => {
    console.log("@@ array", value);
    let localArray = localPreRoutingCall;
    var index = _.findIndex(localArray, { id: item.id });
    localArray.splice(index, 1, { ...item, value: value });
    setLocalPreRoutingCall(localArray);
  };

CodePudding user response:

Like said in the comments, you have to pass a key prop to what you're rendering so React knows what changes.

I don't see a reason for you to use the e.persist function when you're passing the value immediately.

import { Fragment } from "react";

localPreRoutingCall?.map((item, i) => (
  <Fragment key={item.id}>
    <div className="pre-route-title">{item.field_title}</div>
    <textarea
      placeholder="Enter something"
      className="pre-route-textarea"
      value={item.value}
      onChange={(e) => changeObjectValue(e.target.value, i)}
    />
    <div className="pre-route-description">
      {item.description}
    </div>
  </Fragment>
))

You also didn't clone the localPreRoutingCall state array before changing its value.

Another reason why React won't know what changed.

const changeObjectValue = (value, i) => {
  const localArray = [...localPreRoutingCall];
  localArray[i].value = value;
  setLocalPreRoutingCall(localArray);
};

CodePudding user response:

One obvious problem I can see is that you aren't giving the mapped components keys.

<> can't be used in map because it can't be passed a key, so this would be an improvement

<React.Fragment key={item.id}>

CodePudding user response:

Instead of using

localArray.splice(index, 1, { ...item, value: value });

Use

localArray[index].value = value

  • Related