递归修剪对象中所有元素的更好方法? [英] A better way to trim all elements in an object recursively?

查看:28
本文介绍了递归修剪对象中所有元素的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类似的对象,

If I have an object like,

const obj = {
    field: {
        subfield: {
            innerObj: { a: ' asdasd  asdas . ' },
            innerArr: ['  s  ', '  ssad . '],
            innerArrObj: [ { b: '   adsad  ' } ],
        }
    }
}

我想出了类似的东西

const trimFields = (data) =>
  _.mapValues(data, (element, k) =>
    _.isArray(element)
      ? element.map((value) =>
          _.isObject(value) ? trimFields(value) : trimText(value)
        )
      : _.isObject(element)
      ? trimFields(element)
      : trimText(element)
  );

但是我想知道是否有更好/更有效的方法来做到这一点?

But I'm wondering if there is a better / more efficient way to do this?

JSFiddle

推荐答案

我会编写一个更通用的 deepMap 函数,然后使用 trimText 和您的对象进行调用.然后,它变得易于重用,并且将对象导航的处理与实际的字段转换分开.有或没有lodash都不难写.这是一个版本:

I would write a more general deepMap function and then call it with trimText and your object. It then becomes easily reusable, and it separates out the handling of object navigation from your actual field transformation. It's not hard to write, either with or without lodash. Here's one version:

const deepMap = (fn) => (obj) => 
  Array .isArray (obj) 
    ? obj .map (deepMap (fn))
  : Object (obj) === obj
    ? Object .fromEntries (Object .entries (obj) .map (([k, v]) => [k, deepMap (fn) (v)]))
  : // else 
    fn (obj)

const trimText = field => typeof field === 'string' ? field .trim () : field;

const obj = {field: {subfield: {innerObj: { a: ' asdasd  asdas . ' }, innerArr: ['  s  ', '  ssad . '], innerArrObj: [ { b: '   adsad  ' } ]}}}

console .log (
  deepMap (trimText) (obj)
)

请注意,由于 trim 已内置在 String.prototype 中,因此我简化了 trimText .

Note that I simplified trimText, since trim is built into String.prototype.

编写此通用版本几乎比一次性版本困难得多,您可以将其重用于其他目的.

Writing this generic version is pretty much no more difficult than a one-off version, and you can reuse it for other purposes.

deepMap (square) ({a: 1, b: [2, 3, 4], c: [{d: 5}, {d: 6}]})
//=> {a: 1, b: [4, 9, 16], c: [{d: 25}, {d: 36}]}

这篇关于递归修剪对象中所有元素的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆