首页 > 解决方案 > 如何将此 foreach 推送循环转换为减速器功能?

问题描述

我目前有一个看起来像这样的函数:

export const getTags = (element: Record<string, any>) => {
  const tags: Record<string, any> = {};
  Object.keys(element).forEach((key: string) => {
    if (element[key] === true) {
      tags[key] = true;
    } else if (element[key] === false) {
      tags[key] = false;
    }
  });
  return tags;
};

你这样称呼它:

const objToCheck = {
  foo: true,
  bar: false,
  baz: true,
  moo: [],
  boo: "hello",
}

const tags = getTags(objToCheck);
// returns: { foo: true, bar: false, baz: true }

我目前通过制作一个空对象并推送到它以一种非常低效的方式来做到这一点,我想知道是否有不同的方法reduce可以正确填充这个对象?使代码更干净。

我的函数的目的是将所有带有布尔值的值提取到具有相同键名和值的新对象中。

标签: javascripttypescript

解决方案


好的解决方案应该是这样的:

export const getTags = (element: Record<string, any>) => {
  return Object.fromEntries(
    Object.entries(element)
      .filter(([key,val]) => val instanceof Boolean)
  );
};

我们只是过滤掉非布尔值


推荐阅读