user5536767
user5536767

Reputation:

Collecting a list of all object keys that meet certain criteria

I have a function getActiveProp:

const getActiveProp = obj => Object.keys(obj).find(k => obj[k].active);

But now, instead of finding the first item matching the criteria, I want to get an array of all of them.

I know I could simply do something like this, and wrap it in a function:

var arr = ['foo', 'bar', 'baz'];
var arr2 = [];
arr.forEach(k => arr2.push(k));

But I was just wondering if there was a one-line way to do it, creating the array within the forEach method itself, or using some similar array method to do it. Can that be done?

Upvotes: 1

Views: 532

Answers (1)

gyre
gyre

Reputation: 16779

Use Array#filter in place of Array#find:

let object = {
  inactiveProp1: { active: false },
  activeProp1: { active: true },
  activeProp2: { active: true }
}

const getActiveProps = o => Object.keys(o).filter(k => o[k].active)

console.log(getActiveProps(object))

Upvotes: 3

Related Questions