递归地修剪对象键和值中的空格 [英] Trim white spaces in both Object key and value recursively

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

问题描述

如何在 JavaScript 对象中递归地修剪键和值中的空格?

How do you trim white spaces in both the keys and values in a JavaScript Object recursively?

我遇到了一个问题,我试图清理"用户提供的 JSON 字符串并将其发送到我的其他代码中以供进一步处理.

I came across one issue in which I was trying to "clean" a user supplied JSON string and send it into my other code for further processing.

假设我们有一个用户提供的 JSON 字符串,其属性键和值的类型为字符串".然而,在这种情况下的问题是键和值并不像期望的那样干净.说一个 { " key_with_leading_n_trailing_spaces ": " my_value_with_leading_spaces" }.

Let's say we've got a user supplied JSON string whose property key and value are of type "string". However, what's problematic in this case is that the keys and values are not as clean as desired. Say a { " key_with_leading_n_trailing_spaces ": " my_value_with_leading_spaces" }.

在这种情况下,它很容易导致您编写出色的 JavaScript 程序尝试使用此类数据(或者我们应该称其为脏数据?),因为当您的代码试图从这个 JSON 对象中获取值时,不仅key不匹配,value也匹配不上.我环顾了谷歌并找到了一些提示,但没有一种方法可以治愈所有问题.

In this case, it can easily cause issue with your brilliantly written JavaScript program trying to make use of such data(or should we call it dirty data?) because when your code is trying to get the value out of this JSON object, not only the key is not matching but also the value can not be matched. I have looked around google and found a few tips but there is not one cure that cure it all.

鉴于此 JSON 在键和值中包含大量空格.

Given this JSON with lots of white spaces in keys and values.

var badJson = {
  "  some-key   ": "    let it go    ",
  "  mypuppy     ": "    donrio   ",
  "   age  ": "   12.3",
  "  children      ": [
    { 
      "   color": " yellow",
      "name    ": "    alice"
    },    { 
      "   color": " silver        ",
      "name    ": "    bruce"
    },    { 
      "   color": " brown       ",
      "     name    ": "    francis"
    },    { 
      "   color": " red",
      "      name    ": "    york"
    },

  ],
  "     house": [
    {
      "   name": "    mylovelyhouse     ",
      " address      " : { "number" : 2343, "road    "  : "   boardway", "city      " : "   Lexiton   "}
    }
  ]

};

所以这就是我想出的(在使用 lodash.js 的帮助下):

So this is what I came up with ( with help of using lodash.js):

//I made this function to "recursively" hunt down keys that may 
//contain leading and trailing white spaces
function trimKeys(targetObj) {

  _.forEach(targetObj, function(value, key) {

      if(_.isString(key)){
        var newKey = key.trim();
        if (newKey !== key) {
            targetObj[newKey] = value;
            delete targetObj[key];
        }

        if(_.isArray(targetObj[newKey]) || _.isObject(targetObj[newKey])){
            trimKeys(targetObj[newKey]);
        }
      }else{

        if(_.isArray(targetObj[key]) || _.isObject(targetObj[key])){
            trimKeys(targetObj[key]);
        }
      }
   });

}

//I stringify this is just to show it in a bad state
var badJson = JSON.stringify(badJson);

console.log(badJson);

//now it is partially fixed with value of string type trimed
badJson = JSON.parse(badJson,function(key,value){
    if(typeof value === 'string'){
        return value.trim();
    }
    return value;
});

trimKeys(badJson);

console.log(JSON.stringify(badJson));

请注意:我分 1、2 个步骤完成此操作,因为我找不到更好的方法来解决所有问题.如果我的代码有问题或任何更好的地方,请与我们分享.

Note here : I did this in a 1, 2 steps because I could not find a better one shot to deal it all solution. If there is issue in my code or anything better, please do share with us.

谢谢!

推荐答案

您可以使用 Object.keys 清理属性名称和属性以获得键的数组,然后使用 Array.prototype.reduce 迭代键并创建一个带有修剪过的键和值的新对象.该函数需要递归,以便它还可以修剪嵌套的对象和数组.

You can clean up the property names and attributes using Object.keys to get an array of the keys, then Array.prototype.reduce to iterate over the keys and create a new object with trimmed keys and values. The function needs to be recursive so that it also trims nested Objects and Arrays.

注意它只处理普通的数组和对象,如果你想处理其他类型的对象,对reduce的调用需要更复杂的来确定对象的类型(例如anew obj.constructor() 的巧妙版本.

Note that it only deals with plain Arrays and Objects, if you want to deal with other types of object, the call to reduce needs to be more sophisticated to determine the type of object (e.g. a suitably clever version of new obj.constructor()).

function trimObj(obj) {
  if (!Array.isArray(obj) && typeof obj != 'object') return obj;
  return Object.keys(obj).reduce(function(acc, key) {
    acc[key.trim()] = typeof obj[key] == 'string'? obj[key].trim() : trimObj(obj[key]);
    return acc;
  }, Array.isArray(obj)? []:{});
}

这篇关于递归地修剪对象键和值中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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