-3

I have the following JSON:

"menu":[
    {
        "name": "Home",
        "icon": "ri-home-4-line",
        "layoutCode": "",
        "active": ["h1"]
    },
    {
        "name": "Cust", 
        "layoutCode": "",
        "icon": "ri-user-2-fill",
        "active": ["c1", "c2"]

    }
]

What I would like to do is filter by active and get the parent object.

I tried with this:

json_menu.menu.filter(record => record.active === 'c1')

but i obtain an empty object.

  • _"I have the following JSON:..."_ - No you don't. That's just an object (if we assume that you just missed to also post the wrapping `{ }`) with a `"menu"` property that stores an array of objects... -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Aug 10 '22 at 08:35
  • _"but i obtain an empty object."_ - Because `"active"` is an array... – Andreas Aug 10 '22 at 08:36

4 Answers4

2

You need to check if active includes "c1".

const menu = [
  {
    name: "Home",
    icon: "ri-home-4-line",
    layoutCode: "",
    active: ["h1"]
  },
  {
    name: "Cust",
    layoutCode: "",
    icon: "ri-user-2-fill",
    active: ["c1", "c2"]
  }
];

const result = menu.filter(m => m.active.includes("c1"));
console.log(result);
Behemoth
  • 5,389
  • 4
  • 16
  • 40
0

activeis an array. Try:

json_menu.menu.filter(record => record.active.includes('c1'))
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
0

You can use includes instead of ===

json_menu.menu.filter(record => record.active.includes('c1'))
dinakajoy
  • 126
  • 2
  • 7
0

json_menu.menu.filter(record => record.active.includes('c1'))

use includes function to check item in array