简体   繁体   中英

Return all property names that share the same value in JS Object

I have an array of objects and I want to return array containing only the names of the happy people and return all names when everybody is happy. The thing I fail to get is to get all names when everybody is happy. Any ideas?

EDIT: This is the object.

  [
  { name: 'Don', disposition: 'Happy' },
  { name: 'Trev', disposition: 'Happy' },
]

function findHappyPeople(people) {

var happyPeople = Object.keys(people).filter(function(key) {
   if(people[key] === 'Happy') {
     return people[name]
   }
});

return happyPeople;

}

You have an array of objects, so Object.keys() wouldn't be needed here.

You can use a .map() operation after the filter to end up with an array of names.

Your people[name] code isn't going to work because you have no name variable, except the global one if you're in a browser, which isn't what you want. Your data has a .name property, so use that.

 const data = [ { name: 'Don', disposition: 'Happy' }, { name: 'Trev', disposition: 'Happy' }, ] console.log(findHappyPeople(data)); function findHappyPeople(people) { return people .filter(function(p) { return p.disposition === "Happy" }) .map(function(p) { return p.name }); } 

Or with arrow function syntax:

 const data = [ { name: 'Don', disposition: 'Happy' }, { name: 'Trev', disposition: 'Happy' }, ] console.log(findHappyPeople(data)); function findHappyPeople(people) { return people .filter(p => p.disposition === "Happy") .map(p => p.name); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM