简体   繁体   中英

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.

I've been looking at this SO thread as reference.

I think I am close, but not quite sure what I'm doing wrong.

I have an order that looks like this:

{
    "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 .

// 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.

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",
            ...
        }
    ]
}
  • The order is only returned if the dates match
  • Only the proper purchasables are returned that match (eg FOO)

Currently, I am always getting both purchasables back. I had tried using .some() but was getting the same result.

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:

this.items = this.orders.filter(order => dayjs(order.createdAt).isSame(this.day, "date")).map(item => ({...item, purchasables: item.purchasables.filter(p => p.type == 'FOO') }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM