0

I am trying to display/append my Java script object on the webpage. I want to display each key and it's corresponding value.

Most of the questions that are similar to mine only have answers that suggest to log it to the console or alert it. Unfortunately, this is not what I want.

I have also tried JSON.stringify(), however this seems to just display a blog of text. If JSON.stringify() is the only way to print/output the objects key/values pairs to the document, is there anyway to style it?

The following is some that I have tried but with no prevail.

JSON.stringify(object, null, 4));

object.__proto__.toString();

Here is an example of what I want:

Name: John
Name: Bob
Name: Thomas

Without any JSON format curly brackets or any other formatting. Just plain text.

EDIT: I am indeed familiar with document.write(), this is not a solution. I need to APPEND to a web page that already has content, the key and value pairs of my Javascript object.

The Javascript object is dynamic and has a unknown length.

Something like this:

$('#container').html(object);
$('#container').append(object);
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Lars Peterson
  • 1,508
  • 1
  • 10
  • 27

3 Answers3

1

const items =  { 'name': 'John', 'Rank': 2, 'Country': 'USA'  }

output.textContent = JSON.stringify(items, null, 2);
<pre id="output"></pre>  
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
1

You can do something like this:-

var mydata = {'Ram':'100 points','Shyam':'200 points','Fred-ii':'800 points'};

$.each(mydata,function(key,value){
   $('#my-div').append("<span>"+key +":- "+value+"</span>")

});
#my-div{
float:left;
width:100%;
background:rgb(249, 247, 249);
}

#my-div span {
    float: left;
    width: 100%;
}

span:nth-child(even){
  color:green;
}
span:nth-child(odd){
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my-div"></div>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
-1

Loop through object in this way and do your work with key and value-

for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + " -> " + obj[key]);
}
}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Osama
  • 2,912
  • 1
  • 12
  • 15