noo*_*ook 1 javascript ecmascript-6
我想从我的对象中删除值等于 的键null。
我利用了与减速器结合使用的filter功能Object.entries。
我设法创建了这个片段,但它有一个漏洞:如果任何键包含一个 falsey 值,reducer 将返回错误的值:
const obj = {
  boolKey: true,
  intKey: 1,
  nullKey: null,
  falseyKey: 0,
  stringKey: 'string',
};
const result = Object.entries(obj)
  .filter(([, value]) => value !== null)
  .reduce((accumulator, [key, value]) => (accumulator[key] = value) && accumulator, {});
console.log(result); // 0
但是有了这个对象,结果正如预期的那样:
const obj = {
  boolKey: true,
  intKey: 1,
  nullKey: null,
  stringKey: 'string',
};
const result = Object.entries(obj)
  .filter(([, value]) => value !== null)
  .reduce((accumulator, [key, value]) => (accumulator[key] = value) && accumulator, {});
console.log(result);
// { boolKey: true, intKey: 1, stringKey: 'string' }
我知道还有其他方法可以实现这一点,但我想知道如何安全地利用减速器中的隐式返回。
您的回调函数不会在每次调用时返回一个对象作为累加器。只有当value您分配的值为真并且当前累加器是一个对象时,您才返回一个对象。例如,whenvalue为 0,  value  为假,因此accumilator[key] = value将返回0。由于&&算子的LHS为falsy,会短路,导致0返回falsy值。解决此问题的一种方法是使用逗号运算符:
const obj = { boolKey: true, intKey: 1, nullKey: null, falseyKey: 0, stringKey: 'string', };
const result = Object.entries(obj)
  .filter(([, value]) => value !== null)
  .reduce((accumulator, [key, value]) => (accumulator[key] = value, accumulator), {});
console.log(result);或者通过使用扩展语法减少到一个对象:
const obj = { boolKey: true, intKey: 1, nullKey: null, falseyKey: 0, stringKey: 'string', };
const result = Object.entries(obj)
  .filter(([, value]) => value !== null)
  .reduce((acc, [key, value]) => ({...acc, [key]: value}), {});
console.log(result);