0

I want to be able to type localhost:3000/courses/1 and be able to get to show only the object in the json file from the id: 1.

I have a route to the site courses that looks like this and it displays my JSON file in the view when i loop through it just as it should. The js:json is my JSON file that I have required.

    app.get('/courses', function(req, res) {
    res.render('courses', {
        title: "Hello",
        name: "Fredrik",
        js: json
    });
});

[
{
"id":1,"courseId":"DT162G","courseName":"Javascript-baserad webbutveckling","coursePeriod":1
},
{
"id":2,"courseId":"IK060G","courseName":"Projektledning","coursePeriod":1
},
{
"id":3,"courseId":"DT071G","courseName":"Programmering i C#.NET","coursePeriod":2
}
]

But how can i make a route to show only one specific part of the JSON file when i type localhost:3000/courses/1 or /2 or /3?

So that the view looks like this..

 "id":1,"courseId":"DT162G","courseName":"Javascript-baserad webbutveckling","coursePeriod":1

2 Answers 2

1
app.get('/courses/:id', function(req, res) {
    res.render('courses', {
        title: "Hello",
        name: "Fredrik",
        js: req.params.id !== undefined ? json.filter(function(obj) {return obj.id== req.params.id};}) : json
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfect! Im really new to Node so it would be awsome if you could explain how the code works!
0

you may need to add a parameter to your route

app.get('/courses/:id', function(req, res) {
    res.render('courses', {
        title: "Hello",
        name: "Fredrik",
        js: getData(req.params.id)
    });
});

then a simple function that returns your object

function getData (id) { 
   if(typeof id == "undefined") {
       return json;
   }

   for(var i in json) { 
      if(json[i].id == id) {
         return json[id];
      }
   }
}

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.