[英]Filter an array inside an object inside an object inside in array of objects
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.所以这通过一个 GraphQL 解析器。 I have a ID that comes from an input and what I want to do is to filter the array of objects.
我有一个来自输入的 ID,我想做的是过滤对象数组。
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.所以,我想通过对象数组 map,在每个 object 中输入 parentPost 属性,然后获取 parentPost._id 并与我的输入进行比较,以便过滤它。 If the [Array].object.parentPost_id matches my input then I would like to return that whole object.
如果 [Array].object.parentPost_id 与我的输入匹配,那么我想返回整个 object。
I'm thinking something along the lines object.我正在考虑 object。
arrayOfObjects.map(object => object.parentPost._id.find(el => el === input))
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.您的猜测不会过滤,原因有两个:它映射了
arrayOfObjects
,所以总是将它们全部返回,并且_id
不是一个数组,所以.find()
不会做你想做的事。
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. filter
通过遍历所有项目返回一个新数组,并仅获取在条件中返回true
的那些。 The object.parentPost._id === input
just checks if the _id
matches your input
. object.parentPost._id === input
只是检查_id
是否与您的input
匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.