Home > Blockchain >  How do I update an array of object property value with input form in javascript?
How do I update an array of object property value with input form in javascript?

Time:05-23

I'm currently learning node.js, express.js and handlebars

I have 2 forms, add form and edit form to make a blog/news kind of page

/addproject:

app.get('/addproject', function(req, res) {

    res.render('addproject', { title: "Add Project", apActive: true, active: "active" })
})

app.post('/addproject', function(req, res) {

    const projectImage = req.body.projectImage;
    const projectTitle = req.body.projectTitle;
    const projectContent = req.body.projectContent;

    const projectDate = {
        startDate: req.body.projectStartDate,
        endDate: req.body.projectEndDate
    }
    const projectTech = {
        checkHtml: req.body.checkHtml,
        checkNode: req.body.checkNode,
        checkCss: req.body.checkCss,
        checkReact: req.body.checkReact
    }

    let month = [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sept",
        "Oct",
        "Nov",
        "Dec"
    ]

    let endDate = new Date(projectDate.endDate)
    let startDate = new Date(projectDate.startDate)

    function getProjectDuration(endDate, startDate) {

        endDate = new Date(projectDate.endDate)
        startDate = new Date(projectDate.startDate)

        const distance = endDate - startDate

        const miliseconds = 1000
        const secondInMinute = 60
        const minuteInHour = 60
        const secondInHour = secondInMinute * minuteInHour // 3600
        const hourInDay = 23
        const dayInMonth = 30

        let dayDistance = distance / (miliseconds * secondInHour * hourInDay)

        if (dayDistance >= 30) {
            return `${Math.floor(dayDistance / dayInMonth)}`   ` Bulan`
        } else {
            return `${Math.floor(dayDistance)}`   ' Hari'
        }
    }

    const projectDetailDate = {

        edDate: endDate.getDate(),
        edMonth: month[endDate.getMonth()],
        edYear: endDate.getFullYear(),
        sdDate: startDate.getDate(),
        sdMonth: month[startDate.getMonth()],
        sdYear: startDate.getFullYear()
    }

    const projectDuration = getProjectDuration()

    const projectData = {
        projectImage,
        projectTitle,
        projectContent,
        projectDate,
        projectDuration,
        projectTech,
        projectDetailDate
    }

    project.push(projectData)

    res.redirect('/')

})
<!DOCTYPE html>
<html lang="en">

{{> head}}

<body>
    {{> navbar}}

    <!--ADD PROJECT-->
    <div >
        <p>ADD PROJECT</p>
    </div>
    <div >
        <form action="/addproject" method="POST">
            <div >
                <label for="projectInputName" >Project Name</label>
                <input type="text"  id="projectInputName" aria-describedby="emailHelp" name="projectTitle">
            </div>
            <div  style="gap: 10px;">
                <div >
                    <label for="projectInputStartDate" >Start Date</label>
                    <input type="date"  id="projectInputStartDate" name="projectStartDate">
                </div>
                <div >
                    <label for="projectInputEndDate" >End Date</label>
                    <input type="date"  id="projectInputEndDate" name="projectEndDate">
                </div>
            </div>
            <div >
                <label for="projectDescription">Description</label>
                <textarea id="projectDescription"  name="projectContent"></textarea>
            </div>
            <div >
                <label for="checkTitle">Technologies</label>
                <div >
                    <div >
                        <div>
                            <label for="checkHtml" >HTML
                            <input type="checkbox" id="checkHtml" name="checkHtml">
                            <span ></span>
                        </label>
                        </div>
                        <div>
                            <label for="checkNode" >Node Js
                            <input type="checkbox" id="checkNode" name="checkNode">
                            <span ></span>
                        </label>
                        </div>
                    </div>
                    <div >
                        <div>
                            <label for="checkCss" >CSS
                            <input type="checkbox" id="checkCss" name="checkCss">
                            <span ></span>
                        </label>
                        </div>
                        <div>
                            <label for="checkReact" >React Js
                            <input type="checkbox" id="checkReact" name="checkReact">
                            <span ></span>
                        </label>
                        </div>
                    </div>
                </div>
            </div>
            <div>
                <label>Upload Image</label>
                <div >
                    <label for="inputImage">
            <div >Choose</div>
            <div ><i ></i></div>
            </label>
                    <input type="file" id="inputImage" name="projectImage" hidden />
                </div>
            </div>
            <div >
                <button type="submit">Submit</button>
            </div>
        </form>
    </div>
    <!--ADD PROJECT END-->

</body>

</html>

/editproject:

app.get('/editproject/:id', function(req, res) {

let data = req.params.id

let edit = project[data]

res.render('editproject', { title: 'Edit Project', editForm: edit })
})

app.post('/editproject', function(req, res) {


    let projectEdit = project.map(function(data) {

        return {
            ...data = req.body
        }
    })

    project.push(projectEdit)

    res.redirect('/')

})
<!DOCTYPE html>
<html lang="en">

{{> head}}

<body>
    {{> navbar}}
    <!--ADD PROJECT-->
    <div >
        <p>EDIT PROJECT</p>
    </div>
    <div >
        <form action="/editproject" method="POST">
            <div >
                <label for="projectInputName" >Project Name</label>
                <input type="text"  id="projectInputName" value="{{ editForm.projectTitle }}" aria-describedby="emailHelp" name="projectTitle">
            </div>
            <div  style="gap: 10px;">
                <div >
                    <label for="projectInputStartDate" >Start Date</label>
                    <input type="date"  id="projectInputStartDate" name="projectStartDate">
                </div>
                <div >
                    <label for="projectInputEndDate" >End Date</label>
                    <input type="date"  id="projectInputEndDate" name="projectEndDate">
                </div>
            </div>
            <div >
                <label for="projectDescription">Description</label>
                <textarea id="projectDescription"  name="projectContent">{{ editForm.projectContent }}</textarea>
            </div>
            <div >
                <label for="checkTitle">Technologies</label>
                <div >
                    <div >
                        <div>
                            <label for="checkHtml" >HTML
                            <input type="checkbox" name="checkHtml" {{#if editForm.projectTech.checkHtml}} checked {{/if}}>
                            <span ></span>
                        </label>
                        </div>
                        <div>
                            <label for="checkNode" >Node Js
                            <input type="checkbox" id="checkNode" name="checkNode" {{#if editForm.projectTech.checkNode}} checked {{/if}}>
                            <span ></span>
                        </label>
                        </div>
                    </div>
                    <div >
                        <div>
                            <label for="checkCss" >CSS
                            <input type="checkbox" id="checkCss" name="checkCss" {{#if editForm.projectTech.checkCss}} checked {{/if}}>
                            <span ></span>
                        </label>
                        </div>
                        <div>
                            <label for="checkReact" >React Js
                            <input type="checkbox" id="checkReact" name="checkReact" {{#if editForm.projectTech.checkReact}} checked {{/if}}>
                            <span ></span>
                        </label>
                        </div>
                    </div>
                </div>
            </div>
            <div>
                <label>Upload Image</label>
                <div >
                    <img src="/public/assets/{{ editForm.projectImage }}" alt="">
                </div>
                <div >
                    <label for="inputImage">
            <div >Choose</div>
            <div ><i ></i></div>
            </label>
                    <input type="file" id="inputImage" name="editImage" onChange={data => editForm(data)} hidden />
                </div>
            </div>
            <div >
                <button type="submit">Submit</button>
            </div>
        </form>
    </div>
    <!--ADD PROJECT END-->
</body>

</html>

/index (blog thumbnail only):

app.get('/', function(req, res) {

    let cardData = project.map(function(data) {
        return {
            ...data
        }
    })

    res.render('index', {
        title: "Home",
        homeActive: true,
        active: "active",
        card: cardData,

    })
})
<!--MP = My Project-->
        <div >
            <div >
                <p>My Project</p>
            </div>
            <div >
                <div >
                    {{#each card}}
                    <div >
                        <!--MPC = My Project Card-->
                        <div >
                            <img src="public/assets/{{ this.projectImage }}" alt="Thumbnail Image">
                        </div>
                        <div >
                            <a href="/project-detail/{{ this.projectTitle }}" action="/project-detail" target="_blank">
                                <p>{{ this.projectTitle }}</p>
                            </a>
                            <small>Durasi: {{ this.projectDuration }}</small>
                        </div>
                        <div >
                            {{ this.projectContent }}
                        </div>
                        <div >
                           {{#if this.projectTech.checkHtml}} <i ></i> {{/if}}
                           {{#if this.projectTech.checkCss}} <i ></i> {{/if}}
                           {{#if this.projectTech.checkNode}} <i ></i> {{/if}}
                           {{#if this.projectTech.checkReact}} <i ></i> {{/if}}
                        </div>
                        <div >
                            <a href="/editproject/{{ @index }}" action="/edit-project">Edit</a>
                            <a href="/delete-project/{{ @index }}">Delete</a>
                        </div>
                    </div>
                    {{/each}}
                </div>
            </div>
        </div>
        <!--MP END-->

/project-detail:

app.get('/project-detail/:projectTitle', function(req, res) {

    let data = project.find(item =>
        item.projectTitle === req.params.projectTitle

    )


    res.render('project-detail', { title: "Project Detail", project: data })
})
<!DOCTYPE html>
<html lang="en">

{{> head}}

<body>
    <!--NAV START-->
    {{> navbar}}
    <!--NAV END-->

    <!--Blog Detail-->
    <div id="blog-detail">
        <!--BD = Blog Detail-->
        <div >
            <p>{{ project.projectTitle }}</p>
        </div>
        <!--IDC = Image, Duration, Categories-->
        <div >
            <div >
                <img src="/public/assets/{{ project.projectImage }}" alt="Blog Image">
            </div>
            <div >
                <p>Duration</p>
                <div >
                    <div>
                        <i ></i>
                        <p >{{ project.projectDetailDate.sdDate }} {{ project.projectDetailDate.sdMonth }} {{ project.projectDetailDate.sdYear }} - {{ project.projectDetailDate.edDate }} {{ project.projectDetailDate.edMonth }} {{ project.projectDetailDate.edYear }} </p>
                    </div>
                    <div>
                        <i ></i>
                        <p >{{ project.projectDuration }}</p>
                    </div>
                </div>
                <div >
                    <p>Technologies</p>
                    <div >
                        {{#if project.projectTech.checkHtml }} 
                            <div >
                            <i ></i>
                            <p>HTML</p>
                            </div>
                        {{/if}}
                        {{#if project.projectTech.checkCss }}
                            <div >
                                <i ></i>
                                <p>CSS</p>
                            </div>
                        {{/if}}
                        {{#if project.projectTech.checkNode }}
                        <div >
                            <i ></i>
                            <p>nodeJs</p>
                        </div>
                        {{/if}}
                        {{#if project.projectTech.checkReact}}
                        <div >
                            <i ></i>
                            <p>reactJs</p>
                        </div>
                        {{/if}}
                    </div>
                </div>
            </div>
        </div>

        <div >
            <p>
                {{ project.projectContent }}
            </p>
        </div>
    </div>
    <!--xBlog Detailx-->
</body>

</html>

Main array: let project = []

All of the js code and main array is placed in one file, looks like this:

let project = [] app.get() app.post()

In /editproject page I use:

let projectEdit = project.map(function(data) { return { ...data = req.body }}) to manipulate the array and updating it based on what I input in edit form with req.body, when I console.log(projectEdit) it shows the updated value but when I use console.log(project) it still doesn't change, the value still the same from /addproject, it only updated in the edit form.

My goal is to update an object form the array (all of the blog content value) by index with the edit form.

Been stuck for hours, I have searched and tried many but nothing works.

Thanks in advance.

CodePudding user response:

You need to change the URL to include the project id and then simply update the project by merging both objects.

app.post('/editproject/:id', function(req, res) {


    project[req.params.id] = {
        ...project[req.params.id],
        ...req.body
    };

    res.redirect('/')

})

You also need to send the id to client

app.get('/editproject/:id', function(req, res) {

    let data = req.params.id

    let edit = project[data]
    // pass the data as id property and render it so you can use it in the url
    res.render('editproject', { id: data, title: 'Edit Project', editForm: edit })
})
  • Related