【问题标题】:lodash - transform object value to string with nested keyslodash - 使用嵌套键将对象值转换为字符串
【发布时间】:2018-12-25 19:24:37
【问题描述】:

我想使用 lodash 将对象(嵌套键)的所有值从数字转换为字符串,并将 null 转换为空白。

请帮忙。

来自:

{
 "item1": {
   "key1": 123,
   "key2": "str",
   "key3": null,
   "key4": [1, 1, 1],
   "nestedkey": {
      "nestkey1": {
          "nestkey2": {
              "key1": 12.34,
              "key3": null
          }
      }
   }
 }
}

到:

{
 "item1": {
   "key1": "123",
   "key2": "str",
   "key3": "",
   "key4": [1, 1, 1],
   "nestedkey": {
      "nestkey1": {
          "nestkey2": {
              "key1": "12.34",
              "key3": ""
          }
      }
   }
 }
}

谢谢

【问题讨论】:

  • 你自己尝试过什么吗?
  • 到目前为止你尝试过什么?通常,您不应该在没有首先展示您自己的努力的情况下就 SO 提出问题。谢谢,祝你好运!

标签: javascript lodash


【解决方案1】:

我发现了这个:

const mapValuesDeep = (obj, cb) => {
  if (_.isArray(obj)) {
    return obj.map(innerObj => mapValuesDeep(innerObj, cb));
  } else if (_.isObject(obj)) {
    return _.mapValues(obj, val => mapValuesDeep(val, cb));
  } else if(_.isString(obj) || _.isBoolean(obj)) {
    return obj;
  } else {
    return cb(obj);
  }
};

const result = mapValuesDeep(obj, _.toString)

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2021-02-21
    • 2020-03-23
    • 2015-03-19
    • 2023-01-16
    • 1970-01-01
    • 2021-02-05
    相关资源
    最近更新 更多