Search code examples
javascriptvue.jscomputed-properties

Filter array if it has a specific key value pair


In Vue-JS, I am using a computed property and want to filter an array on the basis of key-value pair, this is my array which contains objects as (in data() {}):

menu_content: [
  {
    title: "Dashboard",
    icon: "dashboard",
    group: false,
  },
  {
    title: "User",
    icon: "account_circle",
    group: true,
    sub_menu_items: [
      {
        title: "Edit",
        sub_group: true,
        sub_group_items: [
          {
            title: "Admin",
            icon: "verified_user",
          },
        ],
      },
    ]
  }
]

Here in this array I have group property which can be false or true, so I have written some code to filter on the basis of this key-value pair as (in computed: {}):

haveSubGroup() {
  this.menu_content.forEach(item => {
    if (item.group)
      return item.sub_menu_items.filter(sub_item => sub_item.sub_group == true);
  });
}

If I console.log() the above return statement, it gives me an observable, and if I use {{ haveSubGroup }} in the <template> I don't see anything!


Solution

  • You know you are breaking the loop by using that return statement in the forEach loop, I have following solution for you, hope it will help!

    haveSubGroup() {
      let temp = [];
      this.menu_content.forEach(item => {
        if (item.group)
          temp.push(item.sub_menu_items.filter(sub_item => sub_item.sub_group == true));
      });
      return temp[0];
    },