Reputation:
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:
[
{
"data": [
{}
],
"Name": "1",
"Type": "Blue"
},
{
"data": [
{}
],
"Name": "2",
"Type": "Red"
},
{
"data": [
{}
],
"Name": "3",
"Type": "Blue"
}
]
Upvotes: 2
Views: 181
Reputation: 45835
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.
const data = [
{
data: [{}],
Name: "1",
Type: "Blue"
},
{
data: [{}],
Name: "2",
Type: "Red"
},
{
data: [{}],
Name: "3",
Type: "Blue"
}
];
const filteredData = data.filter((item) => item.Type === "Blue");
console.log(filteredData);
Upvotes: 5
Reputation: 27192
If I understood your requirement correctly, You have a string "Type: Blue"
and based on this string you have to filtered out the data array dynamically based on the key
as Type and value
as Blue. If Yes, Here you go :
const str = "Type: Blue";
const splittedStr = str.split(':');
const data = [
{
Name: "1",
Type: "Blue"
},
{
Name: "2",
Type: "Red"
},
{
Name: "3",
Type: "Blue"
}
];
const filteredData = data.filter((item) => item[splittedStr[0]] === splittedStr[1].trim());
console.log(filteredData);
Upvotes: 0
Reputation: 635
You can use the Array.prototype.filter() method.
arr.filter(obj => obj.Type == 'Blue');
will give you the array containing only the objects with type Blue.
Upvotes: 0