I am trying to find the best way to filter my array of objects with specific key’s string. Basically what I am trying to achieve is to get the objects which contain "Type":"Blue"
. Here is my data:
JavaScript
x
24
24
1
[
2
{
3
"data": [
4
{}
5
],
6
"Name": "1",
7
"Type": "Blue"
8
},
9
{
10
"data": [
11
{}
12
],
13
"Name": "2",
14
"Type": "Red"
15
},
16
{
17
"data": [
18
{}
19
],
20
"Name": "3",
21
"Type": "Blue"
22
}
23
]
24
Advertisement
Answer
You could use the filter() method. See the snippet below, as well as a definition of the method from MDN:
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
JavaScript
1
20
20
1
const data = [
2
{
3
data: [{}],
4
Name: "1",
5
Type: "Blue"
6
},
7
{
8
data: [{}],
9
Name: "2",
10
Type: "Red"
11
},
12
{
13
data: [{}],
14
Name: "3",
15
Type: "Blue"
16
}
17
];
18
19
const filteredData = data.filter((item) => item.Type === "Blue");
20
console.log(filteredData);