javascript - 递归循环 JavaScript 后使用自定义 HTML 元素作为 JSON 键变量

标签 javascript jquery arrays json object

我有一个 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 标签内。相反,我想要的是每个键更加定制的东西。例如,它看起来更像是:

  • 如果 pf 存在,则绑定(bind)到 <h2>使用自定义字符串
  • 如果 sd 存在于 pf 中,则将值绑定(bind)到 <p class="first">
  • 如果 ld 存在于 pf 中,则将值绑定(bind)到 <p class="second">
<小时/>
  • 如果 nf 存在,则绑定(bind)到 <h2>使用自定义字符串
  • 如果 sd 存在于 pf 中,则将值绑定(bind)到 <p class="first">
  • 如果 ld 存在于 pf 中,则将值绑定(bind)到 <p class="second">
<小时/>
  • 如果 t 存在,则绑定(bind)到 <h2>使用自定义字符串
  • 将数组值绑定(bind)到 <p>
<小时/>

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

最佳答案

正如 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>

关于javascript - 递归循环 JavaScript 后使用自定义 HTML 元素作为 JSON 键变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28447688/

相关文章:

arrays - 将多个 Google 电子表格合并为一张表格

java - 如何获取 json 文件中的每个 json 元素并将它们放入数组中

javascript - jQuery Animate Left 和 Right 只发生一次

javascript - 为什么tsconfig需要编译Javascript文件Angular

jquery - 如何以不带特殊字符的字符串形式返回 JSON 调用

javascript - 切换菜单不工作 JQuery

c - 如何检查双*数组?

javascript - Android WebView 崩溃 "Fatal signal 5 (SIGTRAP)"

javascript - 如何检测浏览器窗口是否为 "near"底部?

javascript - 阅读更多脚本和并排 div 无法正常协同工作