javascript - Pick out object from array using id. Node.js and Express -


i have task school, , working node.js & express. im stuck.

if paste browser http://localhost:3000/courses/2 need course id of 2 in array below. thist part of array...

courses[0] = '{"_id":1,"courseid":"dt162g","coursename":"javascript-baserad webbutveckling","courseperiod":1}'; courses[1] = '{"_id":2,"courseid":"ik060g","coursename":"projektledning","courseperiod":1}'; courses[2] = '{"_id":3,"courseid":"dt071g","coursename":"programmering c#.net","courseperiod":2}'; courses[3] = '{"_id":4,"courseid":"dt148g","coursename":"webbutveckling för mobila enheter","courseperiod":2}'; 

here code

router.get('/:id', function(req, res, next) {      var id = req.params.id;     var get_course = "no course found!";           for(row of courses){             course_id = row;             // problem here             if(course_id.indexof(id) > 0) get_course = row;             //         }      console.log(get_course);     res.contenttype('application/json');     res.send(get_course); }) 

my problem in loop, hade instructions try pick out indexof(), not necessary though. cant work. have tried alot here, solution above know not working.

with solution im getting course id of 6, because of indexof, thats not right u guys can see problem hope.

first of check have array of strings.

you can use array.prototype.map() create new array of objects courses calling json.parse(i) on items.

then can use array.prototype.find() return first element in array satisfies provided testing function:

var courses = ['{"_id":1,"courseid":"dt162g","coursename":"javascript-baserad webbutveckling","courseperiod":1}','{"_id":2,"courseid":"ik060g","coursename":"projektledning","courseperiod":1}','{"_id":3,"courseid":"dt071g","coursename":"programmering c#.net","courseperiod":2}','{"_id":4,"courseid":"dt148g","coursename":"webbutveckling för mobila enheter","courseperiod":2}'],      id = 2,      course = courses.map((i) => json.parse(i)).find((c) => c._id === id);    console.log(course);

note id = 2 request param id.


Comments

Popular posts from this blog

c# SetCompatibleTextRenderingDefault must be called before the first -

C#.NET Oracle.ManagedDataAccess ConfigSchema.xsd -

c++ - Fill runtime data at compile time with templates -