Как получить JSON данных из структуры DOM в javascript? - PullRequest
2 голосов
/ 29 января 2020
<form id="foo-bar-baz-form">
    <input name="bar.baz" value="">
    <input name="baz" value="">
    <input name="foo.bar.baz" value="">
</form>

Мне нужно написать функцию для получения данных JSON, как показано ниже

 {
    "foo": {
        "bar": {
            "baz": ""
        }
    },
    "bar": {
        "baz": ""
    },
    "baz": ""
 }

Мне нужно написать функцию, которая принимает идентификатор dom в качестве входных данных и возвращает JSON

function getJSON(id){

   return JSON;
}

I had idea like this

1) loop through children nodes
2) get the name of each children node
3) split the name into array
4) If the array item is not last item, add an object and add the array item as key

Как я могу эффективно вывести JSON из вышеприведенного DOM?

1 Ответ

0 голосов
/ 29 января 2020

Задача немного сложнее, чем идея, которую вы представили. При создании ветвей из «свойств» в именах элементов формы вам понадобится рекурсивная функция, которая будет следовать «пути» до того, как будет установлено значение последнего свойства. Как то так:

function form2Obj(form) {
  if (Object.prototype.toString.apply(form) !== '[object HTMLFormElement]') {
    return;
  }
  const obj = Object.create(null); // The return value
  const inputs = Array.from(form.elements);
  // Creates new properties and values to the return value object
  const addProp = (target, name, element) => {
    const branches = name.split('.');
    // Extract the current name to handle
    const current = branches.shift();
    if (branches.length) {
      // Not the last part of the name
      if (!(current in target)) {
        // The property doens't exist, create it
        target[current] = {};
      }
      // Evaluate the next part of the name
      addProp(target[current], branches.join('.'), element);
    } else {
      // This is the last part of the name, get the value from the element
      target[current] = element.value;
    }
  };
  inputs.forEach(input => {
    addProp(obj, input.name, input);
  });
  return obj;
}

console.log(form2Obj(document.querySelector('#foo-bar-baz-form')));
<form id="foo-bar-baz-form">
  <input name="bar.baz" value="">
  <input name="baz" value="">
  <input name="foo.bar.baz" value="">
</form>

Обратите внимание, что form2Obj возвращает объект, вам еще предстоит преобразовать его в JSON, если JSON действительно необходим. Вот скрипка для тестирования.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...