/    Sign up×
Community /Pin to ProfileBookmark

Node.js – display the first 3 objects of json file

I’m trying to create an HTML template which takes in an array of card objects and uses the data contained within to generate a page to display the list of cards. Basically I have a json file filled with hundreds of cards (for the purpose of this post, I’ve only included a few) and I’m trying to figure out how to print out links for only the first 3 cards. If I were to run my server, my localhost:3000/cards page which is my cards.pug file, creates links for every single card in the json file.

Each link is made up of the card’s name and id, and I’m not quite sure how I would edit my server so that it would only return the first 3 cards instead of all of them. Any help or a push in the right direction would be appreciated!

Server.js:

const pug = require(“pug”);
const fs = require(“fs”);
const http = require(“http”);
const url = require(‘url’)

let cardData = require(“./cards.json”);
let cards = {};
cardData.forEach(card => {
cards[card.id] = card;
});

//Initialize server
const server = http.createServer(function(request, response) {
if (request.method === “GET”) {
if (request.url === “/cards”) {
response.statusCode = 200;
response.write(pug.renderFile(“./views/cards.pug”, { cards: cards }));
response.end();
}else if (request.url.startsWith(“/cards/”)) {
const paths = request.url.split(“/”);
const cardId = paths[2];
if (cards.hasOwnProperty(cardId)) {
const targetCard = cards[cardId];
response.statusCode = 200;
response.write(
pug.renderFile(“./views/card.pug”, { card: targetCard })
);
response.end();
return;
} else {
response.statusCode = 404;
response.end();
return;
}
}
} else {
response.statusCode = 404;
response.write(“Unknown resource.”);
response.end();
}
});

//Start server
server.listen(3000);
console.log(“Server listening at http://localhost:3000”);

cards.json:

[
{
“artist”:”Arthur Bozonnet”,
“attack”:3,
“collectible”:true,
“cost”:2,
“flavor”:”And he can’t get up.”,
“health”:2,
“id”:”AT_003″,
“mechanics”:[“HEROPOWER_DAMAGE”],
“name”:”Fallen Hero”,
“rarity”:”RARE”
},

{
“artist”:”Dan Scott”,
“attack”:3,
“collectible”:true,
“cost”:4,
“flavor”:”Is he aspiring or inspiring? Make up your mind!”,
“health”:5,
“id”:”AT_006″,
“mechanics”:[“INSPIRE”],
“name”:”Dalaran Aspirant”,
“rarity”:”COMMON”
},

{
“artist”:”Andrew Hou”,
“attack”:3,
“cardClass”:”MAGE”,
“collectible”:true,
“cost”:3,
“dbfId”:2571,
“flavor”:”Does he sling spells, or do his spells linger about. Who can say?”,
“health”:4,
“id”:”AT_007″,
“mechanics”:[“BATTLECRY”],
“name”:”Spellslinger”,
“rarity”:”COMMON”,
“set”:”TGT”,
“text”:”<b>Battlecry:</b> Add a random spell to each player’s hand.”,
“type”:”MINION”
},

{
“artist”:”Christopher Moeller”,
“attack”:6,
“cardClass”:”MAGE”,
“collectible”:true,
“cost”:6,
“dbfId”:2544,
“flavor”:”The Grand Tournament has a “No dragons allowed” policy, but it’s rarely enforced.”,
“health”:6,
“id”:”AT_008″,
“name”:”Coldarra Drake”,
“race”:”DRAGON”,
“rarity”:”EPIC”,
“set”:”TGT”,
“text”:”You can use your Hero Power any number of times.”,
“type”:”MINION”
}
]

cards.pug:

html
head
title Cards
body

div#main
h1 List of Cards:
each card in cards
a(href=”/cards/” + card.name) #{card.id}
br

card.pug:

html
head
title #{card.name}
body

div#main
h1 Name: #{card.name}, Cost: $#(card.cost)

My cards.pug page just shows a bunch of links that have the name and id of the card.
So for example, the first card appears as a link that says “Fallen Hero (AT_003)”

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMar 06.2021 — Seems to me that an old fashioned for loop would be more appropriate in this case:
``<i>
</i>const nrCards = 3;
let cardData = require("./cards.json");
let cards = {};
for (let i = 0; i &lt; nrCards &amp;&amp; i &lt; cardData.length; i++) {
cards[cardData[i].id] = cardData[i];
}<i>
</i>
``
Copy linkTweet thisAlerts:
@NogDogMar 06.2021 — @Sempervivum#1628962

Just asking for my edification as a not very good JS coder, could that comparison be done something like:
[code=javascript]
for (let i = 0; i < Math.min(nrCards, cardData.length); i++)
[/code]

?
Copy linkTweet thisAlerts:
@SempervivumMar 06.2021 — Yes, this should be fine either.
Copy linkTweet thisAlerts:
@rpg2009Mar 07.2021 — A bit hacky this

``javascript<i>
</i>const numCards = 3
const cards = {}

cardsData.every((card, i) =&gt;
(i &lt; numCards) ? (cards[card.id] = card) : false
)<i>
</i>
``
×

Success!

Help @marystew spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...