-1

Hi what is the best way to update an array of object based on an id thats exists as a key in object in javascript react js.

My Array of object -

const myData = [
    {
        'id': 1',
        'name': 'A',
        'age': 15
    },
    {
        'id': 2',
        'name': 'B',
        'age': 99
    },
    {
        'id': 3',
        'name': 'C',
        'age': 11
    },
    {
        'id': 4',
        'name': 'D',
        'age': 22
    },
    {
        'id': 5',
        'name': 'E',
        'age': 35
    },
]

I want to update age of id 3. I did it using map function in javascript react but what if it has 1000 records it will take more time. My solution -

const [update , setUpdate] = useState(myData)
 const hello = update.map( item => {
    if(item.id === 3) {
        return {
            ...update,
            age: 100
        }
    }
 });
 setUpdate(hello);

I am achieving my result. But it will take more time if records is 1000 or so. What is the best way to do it ?

Anurag Mishra
  • 647
  • 3
  • 15
  • 31

1 Answers1

-1

find it like this:

let item = myData.find(x=>x.id===3);

then update it like this:

item.age=100
console.log(myData)

it will effect on the array