Skip to content
Advertisement

Find a specific object in an array of objects

I don’t understand because I use the method “find” but I get “undefined”… My data :

[ 
{ "id": 2, "title": "My project", "nameStructure": "Entreprise", "studies": 
    [ 
    {"id": 3, "name": "My stidue", "status": "in prepa" }, 
    { "id": 4, "name": "My second study ", "status": "In"} 
    ], 
    "typeStructure": "Entreprise" 
}, 
{ "id": 3, "title": "My project 2", "nameStructure": "Entreprise 2", "studies": 
    [ 
    {"id": 4, "name": "My stidue 2", "status": "in prepa" }, 
    { "id": 5, "name": "My second study 2 ", "status": "In"} 
    ], 
    "typeStructure": "Entreprise 2" 
}, 
...
 ] 

I would like to have only the object with the ID 2 for example.

So I wrote :

const id = 2
myarray.filter(p => p.id === id);

But it does not work… I always get “undefined”

Thanks for help

Advertisement

Answer

ID is a number, therefore you need to remove the quotes around 2

myarray.filter(p => p.id === 2);

and the operator === in Javascript means that 2 should be equal to “2” as in value and type

reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement