anil kumar
anil kumar

Reputation: 19

Filter object based on condition

I have an object as

sports={
   "cricket":true,
   "football":true,
   "tennis":false
}

I want to filter all the sports which are true into an array like [cricket,football]

Upvotes: 0

Views: 1127

Answers (5)

Klaycon
Klaycon

Reputation: 11090

As posted by @David784 in the comments, this is the simplest solution. No need to complicate it any further:

const sports = {
   cricket:true,
   football:true,
   tennis:false,
};

const result = Object.keys(sports).filter(key => sports[key]);
console.log(result);

Merely get an array of the keys (Object.keys(sports)) and then discard the ones for which the value isn't true with a .filter().

Upvotes: 1

reza babakhani
reza babakhani

Reputation: 89

follow above code returns keys of true value in array like [cricket,football]

const sports = {
  cricket: true,
  football: true,
  tennis: false,
};

const result = Object.keys(sports).filter((current) => {
  return sports[current];
});

Upvotes: 2

Danziger
Danziger

Reputation: 21191

You could use Object.entries(), Array.prototype.filter() and Array.prototype.map() like so:

const sports = {
   cricket:true,
   football:true,
   tennis:false,
};

console.log(Object.entries(sports).filter(([key, value]) => value).map(([key, value]) => key));

Object.entries() returns an array with key-value pairs:

[
  ['cricket', true],
  ['football', true],
  ['tennis', false],
]

You can then check the second element on each entry to filer out the ones that are false:

[
  ['cricket', true],
  ['football', true],
]

And then use map to keep only the first element:

[
  'cricket',
  'football',
]

Upvotes: 1

user13353170
user13353170

Reputation:

var sports_arr = Object.keys(sports);
var tmp = [];
for(var i = 0; i < sports_arr.length && sports[sports_arr[i]]; i++)
  tmp.push(sports_arr[i]);

Upvotes: 1

Juan Moreno
Juan Moreno

Reputation: 11

Use a for...in structure:

sports={
   cricket:true,
   football:true,
   tennis:false
}
const result = []
for(const sport in sports) {
 if (sports[sport]) result.push(sport)
}
console.log(result)

more info about for...in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Upvotes: 1

Related Questions