【问题标题】:Display nested array/object values into separate elements on click单击时将嵌套的数组/对象值显示为单独的元素
【发布时间】:2015-02-03 16:06:23
【问题描述】:

我目前有一个包含几个嵌套数组的对象,其中包含另一个对象和一个只有一个数组的对象。它的格式如下:

{
    "x": 1409529600000,
    "y": 730,
    "pf": [
        {
            "sd": "this is some text"
        },
        {
            "sd": "here is some stuff"
        }
    ],
    "nf": [
        {
            "sd": "im in the nf array"
        },
        {
            "sd": "me too!"
        }
    ],
    "t": [
        "here is a tip",
        "how about the other tip"
    ]
}

当用户单击链接时,我希望将所有这些数据(减去 x: 和 y:)显示到页面上的元素。例如:

from pf:
<p>this is some text</p>
<p>here is some stuff</p>

from nf:
<p>im in the nf array</p>
<p>me too!</p>

from t:

<p>here is a tip</p>
<p>how about the other tip</p>

如您所见,它有点复杂。我需要通过 pf 和 nf 从每个嵌套数组/对象中提取值,并从 t 的数组中提取这两个项目,并将它们全部包装在自己的元素中。

我什至不知道从哪里开始。我知道我可以循环并从这两个对象中获取值,但是将所有内容拉出、将其绑定到元素并显示似乎需要做很多工作。

编辑:为了简单的解决方案,我还可以让后端返回 t: 作为具有键值的对象。

【问题讨论】:

  • 您可能需要更具体一些,您是否要求语法来引用对象内部的数组索引,然后是更新标记的 HTML 内容的语法?
  • 不确定你到底想做什么,但如果你知道如何从父对象中获取数据,但如果你不喜欢你必须这样做,那么也许你应该重构数据(即父对象)
  • 我已重新格式化示例以准确显示 p 标签元素将如何更新/填充 onclick。希望这更有意义。

标签: javascript jquery arrays object


【解决方案1】:

如何使用递归:

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

你的 HTML 看起来像

<button id="myObj">disp</button>
<div id="showObj"></div>

这就是它的工作原理:

首先,您会听到点击按钮的声音

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

然后,on click 它将调用函数showObjData

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]);
        }
    }
}

最后但同样重要的是,buildData() 创建要显示的 HTML 元素

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

这里有一个jsfiddle 供你玩

【讨论】:

  • 非常棒的答案。非常感谢您花时间向我解释这一切以备将来使用。
【解决方案2】:

您需要编写循环对象数组的逻辑并将该对附加到 DOM。你可以使用for in循环。

function start(input) {
        for (key in input) {
            var typeObject = "[object Object]",
                typeArray = "[object Array]";
            if (getType(input) == typeObject) {
                if (getType(input[key]) == typeObject || getType(input[key]) == typeArray) {
                    console.log(key + ":");
                    $("#output").append("from "+key+": <br/>");
                    start(input[key]);
                } else{
                    console.log(key + ":", input[key]);
                     $("#output").append("<p>"+key+":"+input[key]+" </p>");
                }
            } else if (getType(input) == typeArray) {
                if (getType(input[key]) == typeObject || getType(input[key]) == typeArray) {
                    start(input[key]);
                } else {
                    console.log(input[key]);
                     $("#output").append("<p>"+input[key]+" </p>");
                       }
            }
        }
    }
    start(input);

在此处查看完整代码:http://jsfiddle.net/4urd4qtt/1/

【讨论】:

    【解决方案3】:

    试试这个方法:

     var arr={
    	    "x": 1409529600000,
    	    "y": 730,
    	    "pf": [
    	        {
    	            "sd": "short desc1"
    	        },
    	        {
    	            "sd": "short desc2"
    	        }
    	    ],
    	    "nf": [
    	        {
    	            "sd": "short desc1"
    	        },
    	        {
    	            "sd": "short desc2"
    	        }
    	    ],
    	    "t": [
    	        "tip text1",
    	        "tip text2"
    	    ]
    	};
    
    	function show(){
    		var str="";
      for(a in arr){
    	  if( a=="x" || a=="y"){continue;}
    	  str=str+"from "+a+"<br>";
    	  str1="";
    	  for(z in arr[a]){
    		 
    		  if(typeof arr[a][z] === 'object'){
    			  str1=str1+"<p>sd:"+arr[a][z].sd+"</p>";
    				//str1=str1+"<p>"+arr[a][z].toSource()+"</p>"; //this will displace in object format
    		  }else{
                str1=str1+"<p>"+arr[a][z]+"</p>";
    	}
    	
    	}
    	  str=str+str1;
      }
      $("#container2").html(str);// html way of displaying
      console.log(str);// displaying the way written in question
    	}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="click" onclick="show()">click</button>
    
    <div id="container2">
    
    </div>

    【讨论】:

      【解决方案4】:

      试试这个:

      function escapeRegex(string) {
              return string.replace(/[\[\]""(){}?*+\^$\\.|\-]/g, " ");
          }
      
      $('.yourButtonToClick').click(function(){
          var htmlForT="";
          var htmlForPf="";
          var htmlForNf="";
          var pf= escapeRegex(JSON.stringify(json.pf));
          var nf= escapeRegex(JSON.stringify(json.nf));
          var t= escapeRegex(JSON.stringify(json.t));
          //For t
          var arr = t.split(",");
              for (var i = 0; i < arr.length; ++i) {
                  htmlForT+= "<p>"+arr[i]+"</p>";
              }
          $(".yourDisplay").append('<p>for t:</p>').append(htmlForT);
      
          //For pf
          var arr1 = pf.split(",");
              for (var i = 0; i < arr1.length; ++i) {
                  htmlForPf+= "<p>"+arr1[i]+"</p>";
              }
          $(".yourDisplay").append('<p>for pf:</p>').append(htmlForPf);
              //For nf
          var arr2 = nf.split(",");
              for (var i = 0; i < arr2.length; ++i) {
                  htmlForNf+= "<p>"+arr2[i]+"</p>";
              }
          $(".yourDisplay").append('<p>for nf:</p>').append(htmlForNf);
              });
      

      【讨论】:

        猜你喜欢
        • 2014-08-15
        • 2021-11-15
        • 2017-03-27
        • 2023-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多