[英]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. 您有一个对象数组,因此这里不需要Object.keys()
。
You can use a .map()
operation after the filter to end up with an array of names. 您可以在过滤器后使用.map()
操作,以最后一个名称数组结尾。
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. 您的people[name]
代码无法使用,因为您没有name
变量,只有全局变量(如果您使用的是浏览器)就没有了,这不是您想要的。 Your data has a .name
property, so use that. 您的数据具有.name
属性,请使用该属性。
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); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.