下面是两个函数,它们遍历对象集合,以评估是否有任何items对象的id等于函数的id参数。如果为true,则设置活动标志并将当前变量设置为等于id。
注意:
- 函数longerVersion(id(如果verbose/lenger方法
- 函数shorterVersion(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}}
在函数范围内更新current
是您希望避免的副作用。相反,让它成为函数的返回值。
const items = {1:{id:1,active:false},2:{id:2,active:false}, 3:{id:3,active:false}};
const functionalVersion = (items, id) => Object.values(items).reduce((acc, x) => {
x.active = x.id === id;
return x.active ? id : acc;
}, -1);
let current = functionalVersion(items, 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}}
current = functionalVersion(items, 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}}
当items
id与id不匹配时,函数返回-1
。
我不喜欢表达式中的赋值,但如果这是你的事情,你可以在一行中完成:
const functionalVersion = (items, id) => Object.values(items).reduce((acc, x) => x.active = x.id === id ? id : acc, -1);
假设集合确实是一个普通对象,并且您不需要对象原型链中的属性,那么in
关键字越来越不受欢迎,取而代之的是更新的Object.keys
等
function ecmaVersion(id) {
const key = Object.keys(items).find((key) =>
items[key].active = (items[key].id === id))
return current = items[key]?.id
}
lodash当量将涉及_.findKey
。