Home > Back-end >  Filter the attributes of an object to return only the ones of a certain type
Filter the attributes of an object to return only the ones of a certain type

Time:11-23

I am trying to figure out a way to filter an object to get only the attributes of a certain type.

My object looks like this :

analysis: {
  cultural1: true,
  cultural2: false,
  cultural3: true,
  cultural4: true,
  culturalScore: 75,
  environment1: true,
  environment2: true,
  environment3: true,
  environment4: true,
  environmentScore: 100,
  createdAt: "2021-09-15 11:43:58 -0400",
  id: 543,
  review: 'Lorem ipsum odor'
}

What I want is to get an array of only the boolean attributes of that object. Thank you!

CodePudding user response:

const analysis = {
  cultural1: true,
  cultural2: false,
  cultural3: true,
  cultural4: true,
  culturalScore: 75,
  environment1: true,
  environment2: true,
  environment3: true,
  environment4: true,
  environmentScore: 100,
  createdAt: "2021-09-15 11:43:58 -0400",
  id: 543,
  review: 'Lorem ipsum odor'
};

const keysWithBooleanValues = 
  Object.keys(analysis)
  .filter(k => typeof analysis[k] == "boolean");

console.log(keysWithBooleanValues);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

use Object.entries to get an array of key,values pair and then filter those values based on their types using typeof.

let analysis =  {
  cultural1: true,
  cultural2: false,
  cultural3: true,
  cultural4: true,
  culturalScore: 75,
  environment1: true,
  environment2: true,
  environment3: true,
  environment4: true,
  environmentScore: 100,
  createdAt: "2021-09-15 11:43:58 -0400",
  id: 543,
  review: 'Lorem ipsum odor'
}

let result_obj = Object.fromEntries(Object.entries(analysis)
.filter(([k,v]) => typeof(v) === 'boolean'))

console.log(result_obj)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related