объяснение рекурсивного Javascript camelCase

#javascript #json #recursion

#javascript #json #рекурсия

Вопрос:

Я пытаюсь понять, как работает эта функция рекурсии для преобразования ключей JSON в camelCase. Может ли кто-нибудь прокомментировать это для каждой строки и / или добавить объяснение? Спасибо!

 function toCamel(o) {
  var newO, origKey, newKey, value;

  if (o instanceof Array) {
    return o.map(function(value) {
      if (typeof value === 'object') {
        value = toCamel(value);
      }

      return value;
    });
  } else {
    newO = {};

    for (origKey in o) {
      if (o.hasOwnProperty(origKey)) {
        newKey = (origKey.charAt(0).toLowerCase()   origKey.slice(1) || origKey).toString();
        value = o[origKey];

        if (value instanceof Array || (value !== null amp;amp; value.constructor === Object)) {
          value = toCamel(value);
        }

        newO[newKey] = value;
      }
    }
  }

  return newO;
}
  

Комментарии:

1. Не было обнаружено JSON. Вы говорите об объектах JavaScript, а не JSON. JSON — это всегда простая строка.

2. Есть мысли по поводу моего ответа?

Ответ №1:

Я прокомментировал код, чтобы объяснить, что происходит, дайте мне знать, если это не имеет смысла! По сути, это просмотр каждого элемента из того, что вы ему передаете (json), и повторная обработка каждого элемента, если это массив или объект. Это преобразование ключа в строку и установка первого символа в нижний регистр.

 // create a test json array;
var json = {
"TestArr": [
    {"TestKey": 1, "ItemIDs": [0, 1, 2, 3, 4]},
    {"TestKey": 2, "ItemIDs": [5, 6, 7, 8, 9]}
  ]
};

function toCamel(o) {
  var newO, origKey, newKey, value
  // if the passed parameter is an Array...
  if (o instanceof Array) {
    // iterate through each item in the array... 
    return o.map(function(value) {
        // if the current item is an object...
      if (typeof value === "object") {
        // send the current item to this function...
        // this time as an oblect
        value = toCamel(value)
      }
      // return the current item
      return value
    });
  // if the passed item is an object...
  } else {
    // create a temporary object
    newO = {}
    // for each key in the object
    for (origKey in o) {
        // check to make sure the object has a property of the current key
      if (o.hasOwnProperty(origKey)) {
        // convert the key to a string, then make the first character in the string lowercase
        newKey = (origKey.charAt(0).toLowerCase()   origKey.slice(1) || origKey).toString()
        // set the value var equal to the current key value
        value = o[origKey]
        // if value is an array OR the value isn't null AND its constructor is an Object...
        // (ensure the value is an array or object)
        if (value instanceof Array || (value !== null amp;amp; value.constructor === Object)) {
            // set value to this function for more processing
          value = toCamel(value)
        }
        // set the temporary object key value to the new processed value or the original value if not an array/object
        newO[newKey] = value
      }
    }
  }
  // return the finished/formatted JSON
  return newO;
}

// set a variable to the value returned from the toCamel function
var test = toCamel(json);
// write out the result in the console
console.log(test);