I want to filter my products by id (remove one).
if I console log it works all right, but the variable does not change, the arr is the same. Why ?
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const path = require('path');
app.use(express.json());
app.use(express.urlencoded());
const js = require('./translation.json');
app.use('/public', express.static('public'));
let mockProducts = [
{
id: '12',
name: 'Gucci Bag3212',
desc: 'Lorem ipsum dolor sit amet.',
photos: [
{
image_id: '15',
photo: 'https://picsum.photos/590/590'
},
],
price: 19.99,
},
{
id: '13',
name: 'Leather Shoes',
desc: 'Lorem ipsum dolor sit amet',
photos: [
{
image_id: '16',
photo: 'https://picsum.photos/590/590'
},
],
price: 19.99,
}
];
app.put('/remove_product/:id', (req, res) => {
mockProducts.filter(el => el.id !== req.params.id);
res.json({});
});
app.listen(4000, () => {
console.log('LISTEN')
});
if I make console log this I get the right product:
id = 12
console.log(mockProducts.filter(el => el.id === req.params.id)) =
{
id: '12',
name: 'Gucci Bag3212',
desc: 'Lorem ipsum dolor sit amet.',
photos: [
{
image_id: '15',
photo: 'https://picsum.photos/590/590'
},
],
price: 19.99,
},
I am very thankful for your help I dont understand why its not working the arr does not change
CodePudding user response:
mockProducts.filter(el => el.id !== req.params.id);
This does not modify mockProducts
but returns a new array. You need to send that back (or assign it to a variable in your function and act on it.)
CodePudding user response:
Because filter
creates a copy of array, so original keeps the same, but you can reassign
mockProducts = mockProducts.filter(el => el.id !== req.params.id);
this get return of filter, and modify original array