单击时将嵌套数组/对象值显示到单独的元素中

Display nested array/object values into separate elements on click

本文关键字:显示 单独 元素 对象 嵌套 数组 单击      更新时间:2023-09-26

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

{
    "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:作为具有键值的对象。

使用递归性怎么样:

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供您玩

您需要编写用于循环对象数组的逻辑,并将该对附加到 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/

尝试按照以下方式操作:

 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>

试试这个:

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