shageek
shageek

Reputation: 11

How to filter an object's properties according to their values?

Let's say I have an object called colors,

const colors = {
  green: "yes",
  red: "no",
  yellow: "yes"
};

Now, how to get results based on the values. Like, the object should exclude the values which have "no". Below is the desired result:

colors = {
  green: "yes",
  yellow: "yes"
};

My attempt:

Object.keys(colors).filter(c => { if(colors[c]==="yes"){ return arr4.push(colors)}})

Upvotes: 1

Views: 86

Answers (4)

Lucio Paiva
Lucio Paiva

Reputation: 20826

Simple and hopefully easy to understand:

const colors = {
  green: "yes",
  red: "no",
  yellow: "yes",
};

for (const key of Object.keys(colors)) {
  if (colors[key] === "no") {
    delete colors[key];
  }
}

That is also a good use case for the new fromEntries() method. If you feel adventurous, try this instead:

const colors = {
  green: "yes",
  red: "no",
  yellow: "yes",
};

const newColors = Object.fromEntries(
  Object.entries(colors)
    .filter(([key, value]) => value === "yes")
);

It has the added benefit of keeping the original object intact, although I find it a bit more difficult to read than my first suggestion.

Upvotes: 1

Ethan Harris
Ethan Harris

Reputation: 1362

Like this

const colors = {
     green:"yes",
     red:"no",
     yellow:"yes"
}
let filteredColors = {}

let filteredKeys = Object.keys(colors).filter(key => {
    return key==="yes"
})

filteredKeys.map(key => {
    filteredColors[key] = "yes"
})

Upvotes: 0

elouassif
elouassif

Reputation: 318

try this :

const colors = {
  green: 'yes',
  red: 'no',
  yellow: 'yes'
}

let result = {}
Object.keys(colors).map((key) => { if(colors[key] == 'yes')  result[key] = colors[key]})
console.log(result)

Upvotes: 0

rakeden
rakeden

Reputation: 192

First of all, try formatting your questions for better readability.

You can filter the Object with native JS functions. See below:

const colors = {
  green: 'yes',
  red: 'no',
  yellow: 'yes'
}

const filtered = Object.keys(colors)
  .filter(key => colors[key] === 'yes')
  .reduce((obj, key) => {
    obj[key] = colors[key];
    return obj;
  }, {});

which will return an object

{green: "yes", yellow: "yes"}

Upvotes: 1

Related Questions