how to get the name of an object from an ID

Viewed 360

How would I get the name of an item from an array such as the one below, using an id? I have tried by using the .find function in javascript but it returns an undefined response.

{
    "products": [
        {
            "name": "Blue T-Shirt",
            "price": 25.99,
            "description": "A lovely t-shirt.",
            "image": "tshirt.png",
            "id": 1
        },
        {
            "name": "Beige",
            "price": 16.49,
            "description": "Some nice beige pants.",
            "image": "pants.png",
            "id": 2
        },
        {
            "name": "Ugly Shirt",
            "price": 27.99,
            "description": "An ugly, gag-gift shirt.",
            "image": "shirt.png",
            "id": 3
        }
    ]
}

and this is how I am finding it:

var slug = req.params.product;

var item = products.find(products => products.id === slug).name;

console.log(item);

Thanks in advance!

1 Answers

Use .find() on the products array:

const data = {"products": [{"name": "Blue T-Shirt", "price": 25.99, "description": "A lovely t-shirt.", "image": "tshirt.png", "id": 1 }, {"name": "Beige", "price": 16.49, "description": "Some nice beige pants.", "image": "pants.png", "id": 2 }, {"name": "Ugly Shirt", "price": 27.99, "description": "An ugly, gag-gift shirt.", "image": "shirt.png", "id": 3 } ] };

const idToFind = 3;

const item = data.products.find((p) => p.id === idToFind);
console.log(item);

{
  "name": "Ugly Shirt",
  "price": 27.99,
  "description": "An ugly, gag-gift shirt.",
  "image": "shirt.png",
  "id": 3
}

If you wish to 'find' an array with multiple objects, take a look at .filter.

const data = {"products": [{"name": "Blue T-Shirt", "price": 25.99, "description": "A lovely t-shirt.", "image": "tshirt.png", "id": 1 }, {"name": "Beige", "price": 16.49, "description": "Some nice beige pants.", "image": "pants.png", "id": 2 }, {"name": "Ugly Shirt", "price": 27.99, "description": "An ugly, gag-gift shirt.", "image": "shirt.png", "id": 3 } ] };

const idsToFind = [ 2, 3 ];

const item = data.products.filter((p) => idsToFind.includes(p.id));
console.log(item);

Related