javascript - 如何用javascript中的类型替换对象的属性值?
问题描述
让我们考虑一个变量obj,它被定义为:
var obj = {
one: "I am a String",
two: {},
three: 3,
four: []
}
现在,让我们想象一个名为replaceWithType()的函数,它可以像这样使用:
var type = replaceWithType(obj)
console.log(JSON.stringify(type))
这输出:
{"one":"string","two":"object","three":"number","four":"array"}
因此,您可以看到replaceWithType()用它们的类型替换值,但我不明白如何构建这个函数。那么,你能给我一个快速演示一下如何做到这一点吗?
解决方案
通过使用Object.entries()
和.reduce()
:
const obj = {
one: "I am a String",
two: {},
three: 3,
four: []
}
const result = Object.entries(obj).reduce((a, [k, v]) => {
a[k] = Array.isArray(v) ? 'array' : typeof v;
return a;
}, {});
console.log(result);
推荐阅读
- reactjs - 无法使用 Firebase 数据库侦听器 setState()
- python - 使网状皮肤透明?
- html - 如何防止用户的浏览器显示页面的缓存版本?
- python - 创建浮点输出列表并对其进行平均
- html - Flex 在网格中的行为不符合预期
- java - 坚持练习循环遍历数组时出错
- linux - 在 Linux 中允许用户在不拥有文件的情况下编辑文件
- linux - 在 Linux 中测量系统调用开销
- android - Google Places API Crash Javalite clash with other Firebase APIs
- sql-server - SQL Server 已安装,但未在 Windows 服务中显示