[英]How can I filter a nested javascript object and return the parent?
I'm trying to filter a nested object into two parts, then return the parent (and siblings) object back if there are any matching siblings to return.我正在尝试将嵌套的 object 过滤成两部分,然后如果有任何匹配的兄弟姐妹要返回,则返回父(和兄弟姐妹) object 。
I've been looking at this SO thread as reference.我一直在看这个 SO线程作为参考。
I think I am close, but not quite sure what I'm doing wrong.我想我很接近,但不太确定我做错了什么。
I have an order
that looks like this:我有一个看起来像这样的order
:
{
"name": "Name",
"email": "email@email.com",
"createdAt": "2021-12-01T21:19:29.682Z",
"purchasables": [
{
"type": "FOO",
...
},
{
"type": "BAR",
...
}
]
}
Any given order can have multiple things within (purchasable).任何给定的订单都可以包含多个东西(可购买)。 I am trying to filter the order date order.createdAt
and then filter the purchasable type .我正在尝试过滤订单日期order.createdAt
,然后过滤可购买类型。
// vue.js
data() {
return {
items: [],
day: dayjs()
};
},
props: {
orders: {
type: Array,
required: false,
default: () => [],
},
},
methods: {
filterPurchasables() {
this.items = this.orders.filter((order) => {
order.purchasables.every((purchasable) => {
console.log('type: ', purchasable.type); // FOO
return purchasable.type === 'FOO';
});
return dayjs(order.createdAt).isSame(this.day, "date");
});
},
},
If I only filter on the order's createdAt
date, things seem to work well.如果我只过滤订单的createdAt
日期,事情似乎运作良好。
this.items = this.orders.filter((order) => {
return dayjs(order.createdAt).isSame(this.day, "date");
});
In the end, what I'm trying to get back is this:最后,我想要找回的是:
{
"name": "Name",
"email": "email@email.com",
"createdAt": "2021-12-01T21:19:29.682Z",
"purchasables": [
{
"type": "FOO",
...
}
]
}
Currently, I am always getting both purchasables back.目前,我总是把两个可购买的东西都拿回来。 I had tried using .some()
but was getting the same result.我曾尝试使用.some()
但得到了相同的结果。
Thank you for any suggestions!感谢您的任何建议!
EDIT编辑
Here is what I have now that seems to be getting the results I am after.这就是我现在所拥有的,似乎正在得到我所追求的结果。 I'm not convinced this is ideal though...我不相信这是理想的...
this.items = this.orders.filter((order) => {
order.purchasables = order.purchasables.filter((p) =>{
return p.type === "FOO";
});
return dayjs(order.createdAt).isSame(this.day, "date");
});
You can filter your data by createdAt
property, and then in the filtered data, you can again filter purchasables
like this:您可以通过createdAt
属性过滤数据,然后在过滤后的数据中,您可以再次过滤purchasables
的商品,如下所示:
this.items = this.orders.filter(order => dayjs(order.createdAt).isSame(this.day, "date")).map(item => ({...item, purchasables: item.purchasables.filter(p => p.type == 'FOO') }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.