首页 > 解决方案 > 评估条件并设置标志和值的最佳表达式

问题描述

下面是两个函数,它们遍历对象集合以评估是否有任何项目对象的 id 等于函数的 id 参数。如果为真,则它设置一个活动标志并将当前变量设置为等于 id。

笔记:

  1. 如果详细/更长的方法,函数 longVersion(id)
  2. 功能更短的版本(id)是我目前的最佳方法

问题

  1. ES6 和/或 lodash 中是否有更好的方法来实现相同的结果?

const items = {1:{id:1,active:false},2:{id:2,active:false}, 3:{id:3,active:false}}
let current = 0;

function longerVersion(id) {
  for (const k in this.items) {
    if (this.items[k].id === id) {
      this.items[k].active = true
      current = id
    } else {
      this.items[k].active = false
    }
  }
}

function shorterVersion(id) {
  for (const k in this.items) {
    items[k].active = items[k].id === id && ((current = id) && true)
  }
}

longerVersion(2);
console.log(current); // expected outcome : (current === 2)
console.log(items); // expected outcome :  items: {1:{id:1,active:false},2:{id:2,active:true}, 3:{id:3,active:false}}

shorterVersion(3);
console.log(current); // expected outcome : (current === 3)
console.log(items); // expected outcome :  items: {1:{id:1,active:false},2:{id:2,active:false}, 3:{id:3,active:true}}

标签: javascriptecmascript-6lodash

解决方案


假设集合确实是一个普通对象,并且您不需要对象原型链中的属性,那么in关键字越来越不赞成 newer Object.keyset al。这是一种使用它的方法,箭头函数和可选链接,是额外的 Ecma-ish:

function ecmaVersion(id) {
    const key = Object.keys(items).find((key) =>
        items[key].active = (items[key].id === id))
    return current = items[key]?.id
}

lodash 等价物将涉及_.findKey.


推荐阅读