Problem with javascript filter in various JSON

Asked

Viewed 120 times

2

I’m trying to capture a certain product for your ID using the filter but there are some problems. It is only returning an empty array.

The products are stored within Categories, that is, there is an array (products) intended only for products of each category.

Structure of JSON Categories

[
    {
        "color": "blue",
        "_id": "5da5c64983f7162720710e81",
        "user_id": "5d9cc90b7120712fc4371f66",
        "name": "Bebida",
        "createdAt": "2019-10-15T13:14:49.748Z",
        "updatedAt": "2019-10-28T21:14:31.816Z",
        "__v": 3,
        "products": [
            {
                "_id": "5db4da74316b5142042d3c42",
                "code": "2",
                "name": "Coca Cola 1L",
                "price": 7
            }
        ]
    },
    {
        "color": "blue",
        "_id": "5db4e706f9400f41ccab9d66",
        "user_id": "5d9cc90b7120712fc4371f66",
        "name": "Lanche",
        "products": [
            {
                "_id": "5db4e71ff9400f41ccab9d67",
                "code": "3",
                "name": "X Salada",
                "price": 8
            }
        ],
        "createdAt": "2019-10-27T00:38:30.812Z",
        "updatedAt": "2019-10-27T00:38:56.001Z",
        "__v": 1
    }
]

Structure of JSON Products

[
    [
        {
            "_id": "5db4da74316b5142042d3c42",
            "code": "2",
            "name": "Coca Cola 1L",
            "price": 7
        }
    ],
    [
        {
            "_id": "5db4e71ff9400f41ccab9d67",
            "code": "3",
            "name": "X Salada",
            "price": 8
        }
    ]
]

Code

  async update(req, res){
    try{
      const { id, category_id } = req.params;
      const { code, name, description, price } = req.body;

      if (!id ||!category_id || !code || !name || (!price && price != 0))
        return res.status(400).json({ success: false, message: "Empty data" });

      // Capturando todas as categorias
      const categories = await Category.find({ user_id: req.user_id });

      if (!categories[0])
        return res.status(200).json({ success: false, message: "No categories found" });

      // Capturando apenas os produtos de todas as categorias
      const products = categories.map((_categories) => {
        return _categories.products;
      });

      // Capturando um produto pelo ID fornecido
      const product = products.filter((_product) => {
        if (_product._id == id)
          return _product;
      });

      return res.json(product);
    }catch(err){
      return res.status(500).json({ success: false, message: "System error" });
    }
  }

Return

[]

3 answers

2


So Victor, is returning empty, because this way you didn’t access the whole json tree to apply the filter:

const products = categories.map((_categories) => {
 return _categories.products;      // aqui existe um array envolvendo
});

To access products you need to indicate the index that involves products, to then access it and pick up the id:

let dados = [
    {
        "color": "blue",
        "_id": "5da5c64983f7162720710e81",
        "user_id": "5d9cc90b7120712fc4371f66",
        "name": "Bebida",
        "createdAt": "2019-10-15T13:14:49.748Z",
        "updatedAt": "2019-10-28T21:14:31.816Z",
        "__v": 3,
        "products": [
            {
                "_id": "5db4da74316b5142042d3c42",
                "code": "2",
                "name": "Coca Cola 1L",
                "price": 7
            }
        ]
    },
    {
        "color": "blue",
        "_id": "5db4e706f9400f41ccab9d66",
        "user_id": "5d9cc90b7120712fc4371f66",
        "name": "Lanche",
        "products": [
            {
                "_id": "5db4e71ff9400f41ccab9d67",
                "code": "3",
                "name": "X Salada",
                "price": 8
            }
        ],
        "createdAt": "2019-10-27T00:38:30.812Z",
        "updatedAt": "2019-10-27T00:38:56.001Z",
        "__v": 1
    }
]

let retorno = dados
              .map(_product => _product.products[0])
              .filter(x => x._id == '5db4da74316b5142042d3c42'); // aqui vai o id

console.log(retorno);

0

It returns an Array [] because the filter method if it does not find what you want to find, it will always return an empty array. So maybe he’s not finding the ID you want. A link to help you: Method Filter Javascript

And a hint, maybe you could use this library that it generates an ID automatically: UUID

  • 1

    Perhaps it would be better to turn this text into a comment attached to the question.

0

Vitor como products is an array and probably will have several records within the same category, if you pass the index as Leandrade said, you may have errors, try to do so:

let dados.find((categorie) => categorie.name === 'Bebida')
         .products.find((product) => product._id === '5db4da74316b5142042d3c42');
console.log(res);

using . find() other than . filter()/. map() the return is the elememto itself and not an array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.