javascript - 如何将此 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
可以正确填充这个对象?使代码更干净。
我的函数的目的是将所有带有布尔值的值提取到具有相同键名和值的新对象中。
解决方案
好的解决方案应该是这样的:
export const getTags = (element: Record<string, any>) => {
return Object.fromEntries(
Object.entries(element)
.filter(([key,val]) => val instanceof Boolean)
);
};
我们只是过滤掉非布尔值
推荐阅读
- javascript - Redux-React:如何将更新后的状态传递给 onChange 函数?
- java - Java - 使用自定义逻辑打印键值对的最大值
- swift - 将图像名称传递给 SwiftUI 中的自定义图像子类
- javascript - Is possible add multiple projects at the same path?
- java - 如何将字符串更改为小写?
- python - TensorFlow 崩溃内存谷歌 colab
- python - 如何在不安装的情况下在应用程序之间共享 python 类?
- css - Rails 5 - Heroku:预编译资产失败(Sass::SyntaxError: Invalid CSS after "...lflings-regular": expected ")
- notifications - 拨打大量电话后,RingCentral 停止在沙盒中发送呼叫通知
- safari - 如何在 Safari 中获取视频的播放头?