Home > Mobile >  How to get a particular value in an object in node js?
How to get a particular value in an object in node js?

Time:11-28

This is my Object:

{
    "title": "Student Details",
    "education": "under graduate",
    "courses": [
        {
            "courseCode": "101",
            "course": "Physics"
        },
        {
            "courseCode": "102",
            "course": "Chemistry"
        },
        {
            "course": "Math",
            "courseCode": "103"
        }
    ],
    "studentId": "xyz202267"
}

I want to get the courseCode when the course name is the input. If I send 'Math', then 103 needs to be returned.

I was able to get all the courseCodes:

let ans = temp.courses.map(obj => obj.courseCode)

How do I get just the code when course is input?

CodePudding user response:

Use find instead of map

let ans = temp.courses.find(obj => obj.course === 'Math' )

console.log(ans?.courseCode)

CodePudding user response:

The following code can be used to solve your problem:
You can use the find method instead of map to find the object needed.
Reference https://www.w3schools.com/jsref/jsref_find.asp
After that, you can check if the object has been found using the ternary operator ?. If found, it will provide the courseCode otherwise, it will provide Course not found string. (You can change it to anything that you see fit to display)
Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

const temp = {
    "title": "Student Details",
    "education": "under graduate",
    "courses": [
        {
            "courseCode": "101",
            "course": "Physics"
        },
        {
            "courseCode": "102",
            "course": "Chemistry"
        },
        {
            "course": "Math",
            "courseCode": "103"
        }
    ],
    "studentId": "xyz202267"
};

let ans = temp.courses.find(obj => obj.course === 'Math' );
ans = ans && ans.courseCode ? ans.courseCode : "Course not found";
console.log(ans);

Hope this helps.

  • Related