Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
BlueHost Web Hosting

Bonsai Boy of New York Bonsai Trees and Accessories

Website Domains Names & Hosting | Domain.com

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


Instant Grammar Checker - Correct all grammar errors and enhance your writing

Liquid Web Cloud VPS Hosting

Disclosure We are a professional Programming & Software Q&A website, that receives compensation from some of the links whose we show you with Information. It means that my content may contain affiliate links.

12,759 questions

17,366 answers

573 users

How to delete an item from JSON object in Node.js and Express

1 Answer

0 votes
// Users.js

const users = [
    {
        id: 52325,
        name: 'SpongeBob',
        age: 23
    },
    {
        id: 19473,
        name: 'Squidward Tentacles',
        age: 35
    },
    {
        id: 58237,
        name: 'Mr. Krabs',
        age: 45
    }
];

module.exports = users;
// routes/users.js

const express = require('express');
const users = require('../Users');
 
const router = express.Router();
    
router.delete('/:id', (req, res) => {
    const found = users.some(users => users.id === parseInt(req.params.id));
    if (found) {
        res.json({msg: `User ${req.params.id} deleted`, 
                  users:users.filter(user => user.id !== parseInt(req.params.id))});
    } else {
        // 400 Bad Request
        res.status(400).json({msg: `User ${req.params.id} not found`})
    }
});
 
module.exports = router;
// index.js

const express = require('express');
    
const app = express();
 
app.use(express.json());
 
app.use('/users', require('./routes/users'))
 
const PORT = process.env.PORT || 8080;
    
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
 
 
 
   
/*
run:
 
Server started on port 8080

On http://localhost:8080/users/19473
{
    "msg": "User 19473 deleted",
    "users": [
        {
            "id": 52325,
            "name": "SpongeBob",
            "age": 23
        },
        {
            "id": 58237,
            "name": "Mr. Krabs",
            "age": 45
        }
    ]
}
 
*/

 




answered Mar 20 by avibootz
...