I am working on a class assignment where I need to make write a Loop. I made an array of objects for houses. I created a For Loop to sort the array by the price of the houses. The array displays in the console of the webpage but not in the actual webpage. Below are the extracts of what the console shows, what the webpage shows, and my code.
console log
(4) [{...}, {...}, {...}, {...}]
0: {id: 'house4', stories: 1, squareFoot: 1130, color: 'white', year: 1961, ...}
1: {id: 'house1', stories: 1, squareFoot: 1285, color: 'beige', year: 2018, ...}
2: {id: 'house2', stories: 1, squareFoot: 1560, color: 'brown', year: 1983, ...}
3: {id: 'house3', stories: 2, squareFoot: 2975, color: 'tan', year: 2008, ...}
length: 4
[[Prototype]]: Array(0)
webpage
[object Object],[object Object],[object Object],[object Object]
I have watched several videos about sorting arrays, but they all only display to the console log. I tried to modify my code to be similar to the example used in my lecture video as well, but still no output.
let houses = [
{id:"house1", stories:1, squareFoot:1285, color:"beige", year:2018, bedrooms:3, bathrooms:2, price:285000},
{id:"house2", stories:1, squareFoot:1560, color:"brown", year:1983, bedrooms:3, bathrooms:3, price:345000},
{id:"house3", stories:2, squareFoot:2975, color:"tan", year:2008, bedrooms:4, bathrooms:3, price:415000},
{id:"house4", stories:1, squareFoot:1130, color:"white", year:1961, bedrooms:2, bathrooms:2, price:215000}];
for (i=0; i<1; i++) {
houses.sort((a, b) => a.price - b.price);
document.getElementById("houses").innerHTML=houses;
}
console.log(houses);
<p id="houses"></p>
-
Some examples of building html output from an array of objects hereJames– James2024年10月06日 03:46:38 +00:00Commented Oct 6, 2024 at 3:46
-
If your assignment is to use FOR to SORT, then have a look here stackoverflow.com/questions/7870961/…mplungjan– mplungjan2024年10月06日 08:50:00 +00:00Commented Oct 6, 2024 at 8:50
-
This question is similar to: HTML page shows [object Object] after I pressed the button instead to show the results. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.tevemadar– tevemadar2024年10月07日 11:01:29 +00:00Commented Oct 7, 2024 at 11:01
-
(and then also see the duplicate chain of the linked question)tevemadar– tevemadar2024年10月07日 11:02:12 +00:00Commented Oct 7, 2024 at 11:02
2 Answers 2
Several things worth noting.
The for loop
Notice that your two statements inside the for
loop do not depend on the index i
:
houses.sort((a, b) => a.price - b.price);
document.getElementById("houses").innerHTML=houses;
That means that you’re just repeating the same operation each time you loop. So no need for the loop! The sort
method sorts the array in one line.
However, if your assignment was to use a for
loop, I’m guessing that you cannot use the built-in sort
method, and that the point is for you to write your own sorting function.
That is up to you; just note that, as it is, the following for
:
for (i=0; i<1; i++)
only loops once. From here on know that you will have to replace the line
houses.sort((a, b) => a.price - b.price);
with your own sorting function.
The HTML output
You have already seen that setting the text of your HTML paragraph as houses
doesn’t display the contents of the array. That is because it is - surprise - an array1. HTML deals with text, so to achieve your goal, you first need to convert houses
into text.
There are several ways to do this, but best practice would probably be to use the JSON.stringify
method, that outputs the representation of an object as a string. You can see its effect in the following snippet:
let houses = [{id:"house1", stories:1, squareFoot:1285, color:"beige", year:2018, bedrooms:3, bathrooms:2, price:285000},
{id:"house2", stories:1, squareFoot:1560, color:"brown", year:1983, bedrooms:3, bathrooms:3, price:345000},
{id:"house3", stories:2, squareFoot:2975, color:"tan", year:2008, bedrooms:4, bathrooms:3, price:415000},
{id:"house4", stories:1, squareFoot:1130, color:"white", year:1961, bedrooms:2, bathrooms:2, price:215000}];
houses.sort((a, b) => a.price - b.price);
document.getElementById("houses").innerHTML = JSON.stringify(houses);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id ="houses"></p>
</body>
</html>
Addendum
In this case, it is probably better to write:
document.getElementById("houses").textContent = JSON.stringify(houses);
; rather than:
document.getElementById("houses").innerHTML = JSON.stringify(houses);
References
1Any other object would behave in the same way.
Comments
innerHTML
converts the object to a string. The string representation of an object is [object Object]
- as you noticed already. You can use JSON.stringify
to display the contents of every object, or extract the values from it (looping through Object.keys
/Object.values
). Here is a snippet doing that.
Edit Bonus: converted to generic function. Added a function to create a table from the houses
Array.
const houses = retrieveSortedHousesArray();
// 1. As plain csv-alike text within p#houses
printAsCSV(document.querySelector(`#houses`), houses);
// 2. As table
createTableFromArrayOfObjects(houses);
// print CSV-alike within [container]
function printAsCSV(container, objects) {
const labels = Object.keys(objects[0]);
// create a header
labels.forEach((key, i) =>
container.append(`${key}${i < labels.length-1 ? `;` : ``}`));
// add separator
container.append(document.createElement(`br`), `-`.repeat(57));
// add the values
objects.forEach((elem, i) => {
const values = Object.values(elem);
container.append(document.createElement(`br`));
values.forEach((value, i) =>
container.append(`${value}${i < values.length - 1 ? `;` : ``}`));
});
// 'caption'
container.prepend( Object.assign(
document.createElement(`div`), {
innerHTML: `CSV-alike created with<br>
<code>printAsCSV(document.querySelector("#houses"), houses)</code>`,
className: `caption`
} ) );
}
// create a table from an array of Objects
function createTableFromArrayOfObjects(objects) {
const table = document.createElement(`table`);
const header = document.createElement(`tr`);
const labels = Object.keys(objects[0]);
// create a header row
labels.forEach(key =>
header.insertAdjacentHTML(`beforeEnd`, `<th>${key}</th>`));
table.append(header);
// convert values to rows
objects.forEach((elem, i) => {
const row = document.createElement(`tr`)
const values = Object.values(elem);
values.forEach(value =>
row.insertAdjacentHTML(`beforeend`, `<td>${value}</td>`));
table.append(row);
});
// caption
table.prepend( Object.assign(
document.createElement(`caption`), {
innerHTML: `Table created with
<code>createTableFromArrayOfObjects(houses)</code>`
} ) );
document.body.append(table);
}
function retrieveSortedHousesArray() {
return [{
id: "house1",
stories: 1,
squareFoot: 1285,
color: "beige",
year: 2018,
bedrooms: 3,
bathrooms: 2,
price: 285000
},
{
id: "house2",
stories: 1,
squareFoot: 1560,
color: "brown",
year: 1983,
bedrooms: 3,
bathrooms: 3,
price: 345000
},
{
id: "house3",
stories: 2,
squareFoot: 2975,
color: "tan",
year: 2008,
bedrooms: 4,
bathrooms: 3,
price: 415000
},
{
id: "house4",
stories: 1,
squareFoot: 1130,
color: "white",
year: 1961,
bedrooms: 2,
bathrooms: 2,
price: 215000
}
].sort((a, b) => a.price - b.price);
}
body {
font-family: monospace;
}
div.caption {
text-align: center;
width: 400px;
border: solid #999 1px;
padding: 0 4px 4px;
margin-bottom: 0.3rem;
font-weight: bold;
line-height: 1.1rem;
}
div.caption code,
table code {
background-color: hsl(210, 8%, 90%);
color: hsl(210, 8%, 5%);
padding: 2px 4px;
border-radius: 4px;
}
table {
border: 1px solid #999;
th {
color: white;
text-align: left;
background-color: black;
padding: 0 4px;
}
td {
padding: 0 4px;
}
td:nth-child(2),
td:nth-child(3),
td:nth-child(6),
td:nth-child(7),
th:nth-child(1),
th:nth-child(8) {
text-align: center;
}
tr:nth-child(even) {
background-color: #eee;
}
caption {
margin-bottom: 4px;
font-weight: bold;
border: solid #999 1px;
padding: 4px;
}
}
<p id="houses"></p>