skip to Main Content

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


  1. 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:

    const updatedProducts = products.with(index, {...products[index], description: e.target.description});
    

    If you can’t support with yet, it is easy enough to polyfill if needed as well.

    Login or Signup to reply.
  2. I doubt you already have the index and you actually mean id. But if you did, this could be a solution using slice:

     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
    }
    ]
    
    // Get item by index (this is not the same as ID!!)
    // As said in the comments, it's hard to know what decides this index you talk about
    let index = 1
    
    // Get the correct item, which is not hard because apparantely we have the index
    let product = products[index]
    
    // Replace the description of this item
    product.description = 'This is changed'
    
    // Replace new item with old item
    products.splice(index,index,product)
    
    // Show new products list
    console.log(products)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search