在递归循环 javascript 之后,将自定义 HTML 元素用于 JSON 关键变量

Use custom HTML elements for JSON key variables after recursive loop javascript

我有一个 JSON 对象,我可以在单击时循环访问它,我用它在 HTML 中显示给最终用户。目前显示非常通用,将所有内容都放在 P 标签中。

我想做的是根据其键构建自定义元素,并且如果其键值为空则不显示项目。到目前为止,这是我正在使用的:

var obj = {
    "x": 1409529600000,
    "y": 730,
    "pf": [
        {
            "sd": "this is some text",
            "ld": "here guy"
        },
        {
            "sd": "here is more yo",
            "ld": "ld over here"
        }
    ],
    "nf": [
        {
            "sd": "im in the nf array",
            "ld": "Hi mom"
        },
        {
            "sd": "me too!",
            "ld": "Where am i"
        }
    ],
    "t": [
        "here is a tip",
        "how about the other tip"
    ]
};

(function(){
    document
      .getElementById('myObj')
      .addEventListener("click",  showObjData);
}());

function buildData(content) {
    var data = document.createElement('p');
    data.innerHTML = content;
    return data;
}

function goThroughObj(obj) {
    var htmlObj,
        property;
    for (property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (typeof obj[property] === "object") {
                goThroughObj(obj[property]);
            } else {
                document
                  .getElementById('showObj')
                  .appendChild(buildData(obj[property]));
            }
        }
    }    
}

 function showObjData() {
    var key,
        title,
        element = document.getElementById('showObj');

     // clear innerHTML in case user click more than once
     element.innerHTML='';

     for (key in obj) {
         // skip anything that is not an array, ie: x, y
        if (obj[key] instanceof Array) {
            title = '<br/>From ' + key + ' : ';
            element.appendChild(buildData(title));
            // use recursive function 
            // to go through each keys/properties
            goThroughObj(obj[key]);
        }
    }
};

这是与之配套的 jfiddle http://jsfiddle.net/kzcm32g8/6/

如您所见,每个条目都放在 P 标签内。相反,我想要的是每个键更自定义的东西。因此,例如它看起来更像:




我的想法是允许我将返回的数据分配给我设置样式的模板。如果值为 null,我会将它们从该模板中排除。

正如 Alexis 所提到的,有可用的库可以使此类事情变得更容易。如果您只需要一个快速而肮脏的 jQuery 解决方案,您可以只检查您关心的每个密钥。如果找到一个键,它的值将是一个对象数组。循环遍历该数组,检查每个对象是否有其他键,然后构建一个 html 字符串,然后将字符串设置为 div 的 html

var obj = {
    "x": 1409529600000,
    "y": 730,
    "pf": [
        {
            "sd": "this is some text",
            "ld": "here guy"
        },
        {
            "sd": "here is more yo",
            "ld": "ld over here"
        }
    ],
    "nf": [
        {
            "sd": "im in the nf array",
            "ld": "Hi mom"
        },
        {
            "sd": "me too!",
            "ld": "Where am i"
        }
    ],
    "t": [
        "here is a tip",
        "how about the other tip"
    ]
};

var myHTML = '';
// check if `obj` has a key named `pf`
if (obj['pf']) {
  // it does, so make a header for `pf`
    myHTML += '<h2>From pf :</h2><br>';
    // `obj['pf']` is an array of objects
    // loop through each object in the array
    $.each(obj['pf'], function(i, e) {
        // ccheck if the current object has a key named `sd`
        if (e['sd']) {
            // it does, make a `p` tag with `first` class 
            // and insert the value for key 'sd' from the current object
            myHTML += '<p class="first">' + e['sd'] + '</p><br>';
        }
        if (e['ld']) {
            // it does, make a `p` tag with `second` class 
            // and insert the value for key 'ld' from the current object
            myHTML += '<p class="second">' + e['ld'] + '</p><br>';
        }
    });
}
// same as above just using the 'nf' key
if (obj['nf']) {
    myHTML += '<h2>From nf :</h2><br>';
   
    $.each(obj['nf'], function(i, e) {

        if (e['sd']) {
            myHTML += '<p class="first">' + e['sd'] + '</p><br>';
        }
        if (e['ld']) {
            myHTML += '<p class="second">' + e['ld'] + '</p><br>';
        }
    });
}
if (obj['t']) {
    myHTML += '<h2>From t :</h2>';
    // here `obj['t']` is just an array of strings not an array of objects
    // just loop through the array inserting the value of each index into a `p` tag
    $.each(obj['t'], function(i, e) {
        myHTML += '<p>' + e + '</p>';
    });
}
$('#test').html(myHTML);
.first{
  background-color:#cccccc;
  
  }

.second{
  background-color:#eeeeee;
  
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>