我有一个有2个人的对象,我希望该函数返回具有相同属性的所有人的数组。
const people = {'Steven': ['football', 'hockey'], 'Maria': ['writing', 'swimming']}
当前函数看起来没有任何进一步的进展:
function people(interests, interest) { return [] }
我希望该功能检查我是否记录“游泳”,它应该打印出Maria
答案 0 :(得分:1)
这就是你要找的东西吗?
const people = {'Steven': ['football', 'hockey'], 'Maria': ['writing', 'swimming']};
let getCommomProps = (arr, prop) => {
return Object.keys(arr).filter((key) => {
return arr[key].includes(prop);
}, 0);
};
console.log(getCommomProps(people, 'football'));
答案 1 :(得分:0)
您可以使用函数reduce
来评估对象并将匹配累积到数组中。
函数includes
用于验证特定兴趣是否存在于人群中。
此方法返回与特定兴趣匹配的整个对象。
const people = {'Steven': ['football', 'hockey'], 'Maria': ['writing', 'swimming']},
interest = "swimming",
result = Object.keys(people).reduce((a, name) => {
if (people[name].includes(interest)) a.push({[name]: people[name]});
return a;
}, []);
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://codepen.io/egomezr/pen/dmLLwP.js"></script>
&#13;