skip to Main Content

I have an array of objects with student information, I want to get a single value that is attached to a particular key using array.map
Here’s the code

let balanceInfo = students.map((student) => {
    if (typeof(student) === Object){
       let balance = student.balance;
       return balance;
    } 
}) 
console.log(balanceInfo)

Where:
students is an array of objects
.balance is a key in the object

When the array is being traversed, I want to get the balance details of each student.

3

Answers


  1. From your .map() it looks like you want the balance of all the students.
    If you want only balance printed in, you can put console while iterating the students array

    students.forEach((student) => {
        console.log(student.balance)
    }) 
    
    Login or Signup to reply.
  2. The problem is in typeof(student) === Object, you should write the object word in lowercase with quotes like "object".

    let students = [
        {
            balance: 100,
        },
        {
            balance: 200,
        },
    ];
    
    let balanceInfo = students.map((student) => {
        if (typeof student === "object") {
            let balance = student.balance;
            return balance;
        }
    });
    
    console.log(balanceInfo);
    Login or Signup to reply.
  3. Your code is mostly correct, but there is a small issue with the typeof check. The typeof operator returns a string, so the comparison should be with the string 'object' rather than the Object constructor. Here’s the corrected code:

    let balanceInfo = students.map((student) => {
        if (typeof student === 'object') {
            let balance = student.balance;
            return balance;
        }
    });
    
    console.log(balanceInfo);
    

    This code will iterate over the students array using map and extract the balance property from each object. The resulting balanceInfo array will contain all the balance values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search