javascript - 评估条件并设置标志和值的最佳表达式
问题描述
下面是两个函数,它们遍历对象集合以评估是否有任何项目对象的 id 等于函数的 id 参数。如果为真,则它设置一个活动标志并将当前变量设置为等于 id。
笔记:
- 如果详细/更长的方法,函数 longVersion(id)
- 功能更短的版本(id)是我目前的最佳方法
问题
- 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}}
解决方案
假设集合确实是一个普通对象,并且您不需要对象原型链中的属性,那么in
关键字越来越不赞成 newer Object.keys
et 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
.
推荐阅读
- html - 为什么文本内容会使列变宽?
- r - 如何在 R 中指定文本分割?
- javascript - 为什么不使用“new”会影响 Javascript 的性能
- r - 删除重复自身的某个键左侧的所有文本
- visual-studio-code - 如何获取用户从 VSCode 扩展打开的 ViewColumns 的数量?
- java - 将 parseUnsignedInt 移植到 java1.7
- c++ - 是否可以定义一个队列列表,其中每个队列可以是不同的类型?
- flutter - 带有 ListView 的应用程序不会启动。显示没有错误
- docker - okd(openshift) pod 未将结果写入磁盘
- excel - 如何使用 Excel VBA 获取 POST 请求的所有表单数据?