确定一个对象是否具有与 true 相同的键

我想要一个函数,它接受一系列操作,将其与用户操作列表进行比较,然后返回用户是否可以执行该操作。


基本上,给出:


const usersActions: { [key: string]: {[key: string]: boolean} } = {

      Bob: { eat: false, drink: false, sleep: true, walk: true },

      Alice: { eat: true, drink: true, sleep: true, walk: false }

};

如果 Bob 或 Alice 可以执行一组特定的函数,该函数就会返回。


enum Actions{

    Eat= 'eat',

    Drink= 'drink',

    Sleep= 'sleep',

    Walk= 'walk'

}


const verifyActions = (name: string, actions: Array<Actions>) => {

    return actions.every((action) => {

        return usersActions[name][action];

    });

}


console.log(verifyActions('Bob', [Actions.Eat, Actions.Sleep])); // false

console.log(verifyActions('Bob', [Actions.Sleep, Actions.Walk])); // true

console.log(verifyActions('Alice', [Actions.Drink, Actions.Eat, Actions.Sleep])); // true

console.log(verifyActions('Alice', [Actions.Sleep, Actions.Walk])); // false

这完全按照我所描述的方式工作,但我忍不住认为有一种更好的方法可以做到这一点,例如比较数组与对象,也许是 Lodash 的单行代码?这让我的大脑有点困惑,并让我有一种挥之不去的感觉,认为还有更优雅的方法。


侃侃尔雅
浏览 127回答 1
1回答

梦里花落0921

您的函数简单易读,只需删除大括号和return:const usersActions = {&nbsp; Bob: { eat: false, drink: false, sleep: true, walk: true },&nbsp; Alice: { eat: true, drink: true, sleep: true, walk: false }};const Actions = {&nbsp; Eat: 'eat',&nbsp; Drink: 'drink',&nbsp; Sleep: 'sleep',&nbsp; Walk: 'walk'}const verifyActions = (name, actions) => actions.every((action) => usersActions[name][action]);console.log(verifyActions('Bob', [Actions.Eat, Actions.Sleep])); // falseconsole.log(verifyActions('Bob', [Actions.Sleep, Actions.Walk])); // trueconsole.log(verifyActions('Alice', [Actions.Drink, Actions.Eat, Actions.Sleep])); // trueconsole.log(verifyActions('Alice', [Actions.Sleep, Actions.Walk])); // false<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>使用 lodash,您可以从对象中选取所有操作userActions[name],然后检查是否所有操作都在true使用_.every(). 然而,这并没有使它更具可读性或更短。const usersActions = {&nbsp; Bob: { eat: false, drink: false, sleep: true, walk: true },&nbsp; Alice: { eat: true, drink: true, sleep: true, walk: false }};const Actions = {&nbsp; Eat: 'eat',&nbsp; Drink: 'drink',&nbsp; Sleep: 'sleep',&nbsp; Walk: 'walk'}const verifyActions = (name, actions) => _.every(_.pick(usersActions[name], actions))console.log(verifyActions('Bob', [Actions.Eat, Actions.Sleep])); // falseconsole.log(verifyActions('Bob', [Actions.Sleep, Actions.Walk])); // trueconsole.log(verifyActions('Alice', [Actions.Drink, Actions.Eat, Actions.Sleep])); // trueconsole.log(verifyActions('Alice', [Actions.Sleep, Actions.Walk])); // false<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript