Ask coding questions

← Back to all posts
"Objects in javascript" I'm confusing can anyone solve this and explain?
Arvind777 (0)

Write a function that takes in a parameter student which is a JavaScript object.
It should print the properties of the object.
For example if we pass following student object to the function:
var student = {
name : "Anil Kapoor",
sclass : "VI",
rollno : 12
};
it should return [name, sclass, rollno]

Commentshotnewtop
SUHASTADIPARTH1 (168)

Are you doing that in C or Javascript?

SUHASTADIPARTH1 (168)

@Arvind777 Then you can do

var student = {
name: "Jack",
age: 15,
hobbies: "playing the guitar",
studentInfo: function() {
return this.name + this.age
}
};

console.log(student.name)
console.log(student.age)
console.log(student.hobbies)
console.log(studentInfo())

Use this.(property name) ==> this refers to the class

You can do this to get the properties.

You can also put a function inside the student var.

Please mark my answer if it helps. Thank you.

Coder100 (10622)

you have to bind that function to the student if you want that to work @SUHASTADIPARTH1

SUHASTADIPARTH1 (168)

@Coder100 No, it works like that too. I tried it on my repl.

SUHASTADIPARTH1 (168)

@Coder100 Of course I did. On my older repls

Arvind777 (0)

@SUHASTADIPARTH1 It should return an array like [name,sclass,rollno] when we pass student as parameter to the function

SUHASTADIPARTH1 (168)

@Coder100 Oh sorry, I meant console.log(student.studentInfo())

SUHASTADIPARTH1 (168)

@Arvind777 Could you mark my answer if it helps? Thank you.

RYANTADIPARTHI (1692)

the way you have written it is correct for js

Coder100 (10622)

coming from the previous philosophy, we have:

function print_props(student)
{
  return Object.keys(student);
}

Object.keys() is like the std::map<T, O>::iterator if that makes sense.

Coder100 (10622)

This is a js object:

let my_obj = {
  
};

Treat them like hashmaps, like in C++: unordered_map

Coder100 (10622)

oh, well, the attached repl was in C @Arvind777

Coder100 (10622)

anyways did my other comment help @Arvind777

Arvind777 (0)

@Coder100 trying, I need the output

Arvind777 (0)

@Coder100 for example function excerciseOne(student){

student = {[name,class,rollno]} // don't know wether it is correct or not
var school = student
return school

}
document.write(exerciseOne('student'));

something like this

Coder100 (10622)

@Arvind777 ok, well, that's incorrect, sorry

function excerciseOne(student){
  return `[${student.name}, ${student.sclass}, ${student.rollno}]`
}
document.write(exerciseOne({
  name : "Anil Kapoor",
  sclass : "VI",
  rollno : 12
}));