首页 > 解决方案 > 如何用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()用它们的类型替换值,但我不明白如何构建这个函数。那么,你能给我一个快速演示一下如何做到这一点吗?

标签: javascriptobjecttypes

解决方案


通过使用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);


推荐阅读