function应该将具有相同属性的项返回到数组中

时间:2018-04-12 14:44:38

标签: javascript

我有一个有2个人的对象,我希望该函数返回具有相同属性的所有人的数组。

const people = {'Steven': ['football', 'hockey'], 'Maria': ['writing', 'swimming']}

当前函数看起来没有任何进一步的进展:

function people(interests, interest) { return [] }

我希望该功能检查我是否记录“游泳”,它应该打印出Maria

2 个答案:

答案 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;
&#13;
&#13;

相关问题