简体   繁体   中英

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

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?

Use find instead of map

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

console.log(ans?.courseCode)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM