H.Solo
H.Solo

Reputation: 79

Object Keys Filtering

How can I pass object keys into an array that are true. So that I can use this array for filtering?
Example Object:

let results = [
      {name: marc, isAlumnus: true, isScholar: true, isTrustee: false},
      {name: franz, isAlumnus: false, isScholar: true, isTrustee: false},
      {name: Hugo, isAlumnus: true, isScholar: true, isTrustee: false},
    ]

And the attempt of a function!

getActiveStatusGroups (results) {
            let res = [];
            res = results.map((item) => {
                if (item) {
                    res.push('isScholar');
                }
            });
          return res;
        },

let statusArray = getActiveStatusGroup(this.results)

Upvotes: 0

Views: 47

Answers (2)

Pushkin
Pushkin

Reputation: 3604

Filtering is pretty simple in JavaScript

The methods name is right there in your title, yet you failed to recognize it. Use filter instead of map. The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Here's your code

let results = [
      {name: marc, isAlumnus: true, isScholar: true, isTrustee: false},
      {name: franz, isAlumnus: false, isScholar: true, isTrustee: false},
      {name: Hugo, isAlumnus: true, isScholar: true, isTrustee: false},
]

getActiveStatusGroups(group) {
  // returns the element if the condition is true
  return results.filter(result => result[group])
}

That's it

console.log(getActiveStatusGroups('isAlumnus'))
console.log(getActiveStatusGroups('isScholar'))
console.log(getActiveStatusGroups('isTrustee'))

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074038

You can get an array of the property names from Object.keys, or an array of [name, value] arrays from Object.entries, depending on what you want to do.

It's kind of hard to tell what output you want as a result, but for instance, this returns an array of arrays, where the inner arrays are the names of the properties for which the value was truthy:

getActiveStatusGroups(results) {
    return results.map(entry =>
        Object.keys(entry).filter(key => entry[key])
    );
}

Live Example:

let results = [
    {isAlumnus: true, isScholar: true, isTrustee: false},
    {isAlumnus: false, isScholar: true, isTrustee: false},
    {isAlumnus: true, isScholar: true, isTrustee: false},
];

function getActiveStatusGroups(results) {
    return results.map(entry =>
        Object.keys(entry).filter(key => entry[key])
    );
}

console.log(getActiveStatusGroups(results));

Upvotes: 1

Related Questions