Reputation: 179
I have the following array of objects:
[
{
likes: [],
_id: 5f254e21fd3e040640de38b2,
content: 'try this',
author: {
posts: [Array],
comments: [],
images: [],
followers: [Array],
following: [],
_id: 5f21cd54ef00270af6126df3,
name: 'Octavian David',
password: '$2b$10$kwqMFk/B.N2wNKC01D8Tt.KezQN3kFQyqXdEcfVizFWmL.HY2/uJe',
email: 'xx.com',
username: 'octaviandd',
createdAt: '1596050772192',
__v: 0
},
parentPost: {
likes: [],
comments: [Array],
_id: 5f254e19fd3e040640de38b1,
author: 5f21cd54ef00270af6126df3,
description: 'asdqwdqwdqd',
picture: 'urllink',
createdAt: '1596280345466',
__v: 0
},
createdAt: '1596280353464',
__v: 0
},
{
likes: [],
_id: 5f25527f1a0f870948f4a150,
content: 'lets try again then',
author: {
posts: [Array],
comments: [],
images: [],
followers: [Array],
following: [],
_id: 5f21cd54ef00270af6126df3,
name: 'Octavian David',
password: '$2b$10$kwqMFk/B.N2wNKC01D8Tt.KezQN3kFQyqXdEcfVizFWmL.HY2/uJe',
email: 'xxxx.com',
username: 'octaviandd',
createdAt: '1596050772192',
__v: 0
},
parentPost: {
likes: [],
comments: [Array],
_id: 5f2552761a0f870948f4a14f,
author: 5f21cd54ef00270af6126df3,
description: 'try ths jow',
picture: 'urllink',
createdAt: '1596281462164',
__v: 0
},
createdAt: '1596281471814',
__v: 0
}
]
So this goes through a GraphQL resolver. I have a ID that comes from an input and what I want to do is to filter the array of objects.
So, I want to map through the array of objects, enter the parentPost property in each object and then get the parentPost._id and compare to my input so I can filter it. If the [Array].object.parentPost_id matches my input then I would like to return that whole object.
I'm thinking something along the lines object.
arrayOfObjects.map(object => object.parentPost._id.find(el => el === input))
Upvotes: 0
Views: 67
Reputation: 1588
Your guess wont filter for two reasons: it maps the arrayOfObjects
so will always return them all, and the _id
is not an array so .find()
wont do what you want.
My suggestion:
arrayOfObjects.filter(object => object.parentPost._id === input);
filter
returns a new array by going through all items and get only those that return a true
in the condition. The object.parentPost._id === input
just checks if the _id
matches your input
.
Upvotes: 1