How can I display a JavaScript object?
If you want to print the object for debugging purposes, use the code:
var obj = {
prop1: 'prop1Value',
prop2: 'prop2Value',
child: {
childProp1: 'childProp1Value',
},
}
console.log(obj)
will display:
Note: you must only log the object. For example, this won't work:
console.log('My object : ' + obj)
Note ': You can also use a comma in the log
method, then the first line of the output will be the string and after that, the object will be rendered:
console.log('My object: ', obj);
Print content of JavaScript object?
If you are using Firefox, alert(object.toSource())
should suffice for simple debugging purposes.
Display JavaScript Object in HTML
This is how you can do it using jQuery (as you mention you'd like to use jQuery first). But it's not the best way how to it. If you're open to learn better methods then check some of the MV* frameworks (AngularJS, Ember etc.). Anyway, here is just an example:
var grocery_list = {
"Banana": { category: "produce", price: 5.99 },
"Chocolate": { category: "candy", price: 2.75 },
"Wheat Bread": { category: "grains and breads", price: 2.99 }
}
var wrapper = $('#wrapper'), container;
for (var key in grocery_list){
container = $('<div id="grocery_item" class="container"></div>');
wrapper.append(container);
container.append('<div class="item">' + key +'</div>');
container.append('<div class="category">' + grocery_list[key].category +'</div>');
container.append('<div class="price">' + grocery_list[key].price +'</div>');
}
jsfiddle here: http://jsfiddle.net/5jhgbg9w/
EDIT: Please, take this really as an example (which is OK since you're learning). As others pointed out - it's not the best method. Try to combine other examples, particularly the ones which do not compose HTML as a string. For easy tasks like this it's straightforward but the more code you would add, the messier the code becomes. I believe your "learning evolution" would get you there anyway :-) Cheers everyone
EDIT (2021): A lot of years have gone by since I answered this question. What about some more modern examples, just for fun? Without jQuery, just ES6:
const grocery_list = {
"Banana": { category: "produce", price: 5.99 },
"Chocolate": { category: "candy", price: 2.75 },
"Wheat Bread": { category: "grains and breads", price: 2.99 }
};
// since "grocery_list" is an object (not an array) we have do Object.keys()
const generatedHtml = Object.keys(grocery_list).reduce((accum, currKey) => accum +
`<div class="grocery_item">
<div class="item">${currKey}</div>
<div class="category">${grocery_list[currKey].category}</div>
<div class="price">${grocery_list[currKey].price}</div>
</div>`, '');
document.getElementById('container').innerHTML = generatedHtml;
.grocery_item{
padding: 5px;
}
.grocery_item:not(:last-child){
border-bottom: 1px solid #ccc;
}
<div id="container"></div>
How can I display a JavaScript Object with Canvas?
I solved it by my own.
First of all I needed to split the image_string
in element values. This is needed because the image_string
is a fully string type. The values in turn are written then to an array for iteration.
let image_string = "eyIxIjoiUEdJK1pUd3ZZajQ4ZFQ1UlBDOTFQanhwUGtVOEwyaytQSFUrZVR3dmRUNTBRVHgxUGpBOEwzVStQR2srZUR3dmFUNDhkVDVZUEM5MVBnPT0ifQ==";
image_string = getCaptchaCheck_code(image_string).split("\"");
image_string = image_string[3];
image_string = getCaptchaCheck_code(image_string)
var nodeText = ""+image_string+""
var newDiv = document.createElement("div");
newDiv.setAttribute('id', 'talltweets')
var childDiv = document.createElement("div");
var regex = /([<][\/][a-zA-Z0-9][>])/gm;
var newstr = nodeText.replace(regex, " ")
regex = /([<][a-zA-Z0-9][>])/gm;
newstr = newstr.replace(regex, "")
var letter = newstr.split(' ');
In the iteration I create new child nodes and write them together.
for (var i = 0; i < letter.length; i++) {
var node = nodeText[nodeText.indexOf(letter[i])-2];
childNode = document.createElement(node);
childNodeText= document.createTextNode(letter[i]);
childNode.appendChild(childNodeText);
newDiv.appendChild(childNode);
}
After the iteration I created an placeholder div container in my HTML files.
Now the placeholder needs to be filled up.
const placeholderElement = document.getElementById("eyIxI");
placeholderElement.appendChild(newDiv);
I also pulled the getCaptchaCheck_code
function up to make sure it is loaded before the html2canvas
function.
function getCaptchaCheck_code(str) {
return decodeURIComponent(escape(this.atob(str)));
}
html2canvas(document.getElementById("talltweets"), {
onrendered: function (canvas) {
var screenshot = canvas.toDataURL("image/png");
document.getElementById("textScreenshot").setAttribute("src", screenshot);
placeholderElement.removeChild(newDiv);
},
});
As you can see in the last code, the placeholderElement
will remove the "captcha text".
The code works now for 100%.
Enjoy.
Display a js object from the console to the html page
by the way, you can't just display or inject an entire object
of data into the textContent
. datas.data[0]
is an object
of data. What you can do instead are:-
A. Just pick one data to be displayed
document.querySelector('.users').textContent = datas.data[0].email
B. Just inject entire new HTML
document.querySelector('.users').innerHTML = `
<h2>${datas.data[0].first_name} ${datas.data[0].last_name} (ID: ${datas.data[0].id})</h2>
<p>${datas.data[0].email}</p>
`
C. Inject all data available
datas?.data?.map((item) => {
let html = `
<h2>${item?.first_name} ${item?.last_name} (ID: ${item?.id})</h2>
<p>${item?.email}</p>
`;
document.querySelector(".users").insertAdjacentHTML("beforeend", html);
});
You can see a working example here: https://codesandbox.io/s/thirsty-hypatia-n3cpn?file=/src/index.js:484-722
how to display an object in the console with javascript like this?
Using OLOO pattern
You can use OLOO (Object linked to other objects) pattern to achieve the inheritance using Object.create method.
const Animal = {
init: function(name, sound) {
this.name = name;
this.sound = sound;
},
makeSound: function() {
console.log(`${this.name} has the sound "${this.sound}"`);
},
};
// inheritance via Object.create
const Cow = Object.create(Animal);
const Sheep = Object.create(Animal);
const Cat = Object.create(Animal);
// any other methods specific to Cat
Cat.purr = function() {
conslo.log(`${this.name} "purrs"`);
};
const animals = [];
// initializing objects
var cow = Object.create(Cow);
cow.init("Cow", "moop");
animals.push(cow);
var sheep = Object.create(Sheep);
sheep.init("Sheep", "bee");
animals.push(sheep);
var cat = Object.create(Cat);
cat.init("Cat", "meow");
animals.push(cat);
// printing
animals.forEach((animal) => {
animal.makeSound();
});
How to display an Object containing other Objects in Vue.js
loop object and then loop the array inside,
here is a working example
https://codesandbox.io/s/eager-leaf-nx2mq?file=/src/App.vue
<template>
<div id="app">
<div v-for="(value, propertyName) in data" :key="propertyName">
<h1>The key of the {{ propertyName }}</h1>
<ul>
<li v-for="(item, index) in data[propertyName]" :key="index">
{{ item }}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
name: "App",
components: {},
data() {
return {
data: {
1: ["15-16", "16-17", "17-18", "18-19"],
2: ["15-16", "16-17", "17-18", "18-19"],
},
};
},
};
</script>
How to show image based on an object property in JavaScript
See if this works to you. I have no key access to this API, so i've made with your fictional data.
Please be sure that your 'icon' is your image URL
https://jsfiddle.net/ep9hsxLf/
let urlJson = [
{ dt: 1643803200, day: 12.84, description: 'clear sky', icon: '01d' },
{ dt: 1643889600, day: 14.56, description: 'overcast clouds', icon: '04d' },
{ dt: 1643976000, day: 14.85, description: 'overcast clouds', icon: '04d' },
{ dt: 1644062400, day: 14.41, description: 'broken clouds', icon: '04d' },
{ dt: 1644148800, day: 14.99, description: 'clear sky', icon: '01d' },
{ dt: 1644235200, day: 15.68, description: 'few clouds', icon: '02d' },
{ dt: 1644321600, day: 14.95, description: 'broken clouds', icon: '04d' },
{ dt: 1644408000, day: 16.37, description: 'overcast clouds', icon: '04d' }
]
var htmlResult = '';
urlJson.forEach(item => {
var date = new Date(item.dt)
htmlResult += `Temperature: ${item.day} ºC<br>
Dia: ${date}<br>
${item.icon}<br><br>`
});
$(".city").html(htmlResult);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="city"></div>
Related Topics
How to Split a String, Breaking At a Particular Character
How to Read a Local Text File in the Browser
Difference Between == and === in JavaScript
How to Create a Two Dimensional Array in JavaScript
Cartesian Product of Multiple Arrays in JavaScript
Create and Save a File With JavaScript
Why Is Setstate in Reactjs Async Instead of Sync
Generate Random String/Characters in JavaScript
Format Number to Always Show 2 Decimal Places
How to Empty an Array in JavaScript
Convert a JavaScript String in Dot Notation into an Object Reference
Jquery: Return Data After Ajax Call Success
Get Image Data Url in JavaScript
Loading Cross-Domain Endpoint With Ajax
Find the Min/Max Element of an Array in JavaScript
Correct Modification of State Arrays in React.Js