I wants to update the array object value on the basis of the index in Javascript ES6 with the following json data and javascript code. I want to update the description.
const products = [
{
"id": 1,
"description": "Milk Powder",
"qty": 2,
"unitprice": 200,
"totalamount": 400
},
{
"id": 2,
"description": "Air Conditioner",
"qty": 5,
"unitprice": 500,
"totalamount": 2500
},
{
"id": 3,
"description": "RC Cars",
"qty": 30,
"unitprice": 800,
"totalamount": 24000
},
{
"id": 4,
"description": "Down Coat",
"qty": 2,
"unitprice": 300,
"totalamount": 600
}
]
Javascript Code
const handleProductName = (e, index) =>{
const item = [...products,[index].description=e.target.value]
}
2
Answers
As discussed in the comments, it appears as though you want to avoid updating the original array of objects (ie: treat it as immutable/read only). Since products is an array and not an object it doesn’t make much sense to spread it into an object like you’re currently doing. I would suggest however using a newer method (introduced after ES6, in ES2023), called .with() which allows you to update an index from your array but produces a new array, without touching the original:
If you can’t support with yet, it is easy enough to polyfill if needed as well.
I doubt you already have the index and you actually mean id. But if you did, this could be a solution using slice: