0

I currently have an object with a few nested arrarys that contain another object and one with just an array. It is formated as such:

{
    "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"
    ]
}

When a user click a link I'd like to display all this data (minus the x: and y:) to elements on the page. For instance:

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>

As you can see its a bit complex. I need to pull out the values from each nested array/object via pf and nf and also pull out the two items from t's array and them wrap them all in their own elements.

I'm just so lost as to where I even begin. I know I can loop through and get the values from the two objects, but it seems like a lot of work to pull everything out, bind it to an element, and display.

EDIT: For easy of a solution I could also have the backend return t: as an object with a key value too.

3
  • You might need to be more specific, are you asking for the syntax to reference an array index inside of an object, and then the syntax to udpate the HTML content of a tag? Commented Feb 3, 2015 at 6:07
  • Not sure exactly what you want to do, but if you know how to get the data out of the parent object, but if you don't like how you have to do it, then maybe you should restructure the data (i.e. the parent object) Commented Feb 3, 2015 at 6:10
  • I've reformatted the example to show exactly how the p tag elements would be updated/fill onclick. Hopefully this makes more sense. Commented Feb 3, 2015 at 6:19

4 Answers 4

1

how about using recursivity :

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

Your HTML looks like

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

this is how it works:

first, you listen for a click on your button

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

then, on click it will invoke the function 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]);
        }
    }
}

last but not least, buildData() creates the HTML element to be displayed

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

here's a jsfiddle for you to play with

Sign up to request clarification or add additional context in comments.

1 Comment

Really fantastic answer. Thanks so much for taking the time to explain it all to me for future use.
0

You need to write logic for looping through array of objects and append the pair to the DOM. You can use for in loop.

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

See complete code here: http://jsfiddle.net/4urd4qtt/1/

Comments

0

try following this way:

 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>

Comments

0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.