簡體   English   中英

如何從javascript中的DOM結構派生JSON數據?

[英]How to derive JSON data from the DOM structure in javascript?

<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 的 id 作為輸入並返回 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

如何以有效的方式從上述 DOM 派生此 JSON?

任務只是比您介紹的想法復雜一點。 當從表單元素名稱中的“屬性”創建分支時,在設置最后一個屬性的值之前,您需要一個遞歸函數來跟隨“路徑”。 像這樣的東西:

 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,您還沒有將其字符串form2Obj JSON。 這是一個用於測試的小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM