user18241178
user18241178

Reputation:

JavaScript, filter array of objects by a specific key's value

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

Answers (3)

Youssouf Oumar
Youssouf Oumar

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

Rohìt Jíndal
Rohìt Jíndal

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

Johnn Smith
Johnn Smith

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

Related Questions