1

I tried to update normal array data its sucessfully updated.but I have a doubt.I pass id in put url and get id to compare the array.its id is there its get data and stored another variable then that variable used to chanage the value.and its automatically change value in original array.How its possible any one can explain

app.js

const courses = [{id:1,product_name:"bourbon"},{id:2,product_name:"bourbon"}]  

router.put('/:id',(req,res) =>
{
    console.log("hello")
    console.log(req.params.id)
    for(let i=0;i<courses.length;i++)
    {
        if(courses[i].id === parseInt(req.params.id))
        {
            let course = courses[i]
            course.name = "hari"

            console.log(courses)
        }
    }

})

My put url
localhost:3000/woc/1

I got Output
[{id:1,product_name:"bourbon"},{id:2,product_name:"hari"}]

1 Answer 1

1

You need to clone the original object. Just use let course = {...courses[i]} or let course = Object.assign({},courses[i]} instead of let course = courses[i].

Objects behave differently from primitive data types. The 'course' variable contains the reference to the element in the original array. So changing it is modifying the original object in the array.

Sign up to request clarification or add additional context in comments.

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.