4
jerry = {
  weight: 178

}

Malcom = {
  weight: 220
}

Bob = {
  Weight: 134

}

people = [jerry, Malcom, Bob]

console.log(people[0]);

I'm trying to get a console.log of the object's name, "jerry". thanks for any and all help!

J. Bones
  • 459
  • 1
  • 5
  • 9
  • 3
    you can't; objects have no internal name and one object can have 50 different vars refer to it... You can look for it in a certain context and make a match, but that's more of a coincidence than a methodology. – dandavis Mar 14 '17 at 21:53
  • 5
    No need to downvote this -- this is one of those things that can be really unclear to a newbie, since one might not have the baseline knowledge to understand the question. – Christopher Ronning Mar 14 '17 at 21:59
  • Readers may want to note [that assigning function objects to variables *does* preserve the variable name as a property](http://stackoverflow.com/questions/41107548/why-does-obj-foo-function-not-assign-the-name-foo-to-the-function), in many cases. It's reasonable to imagine that standard objects could have the same behaviour, but they don't. – Jeremy Mar 14 '17 at 22:08
  • 2
    This topic shouldn't be closed. It can be done by some means depending on in which context the objects were defined. [Here](https://repl.it/GV7L) is a working example. – Redu Mar 14 '17 at 23:31

2 Answers2

5

ES6 Version: Using Object#entries, Array#forEach, and destructuring

const jerry = {weight: 178}
const Malcom = {weight: 178}
const Bob = {weight: 178}

const people = {jerry, Malcom, Bob}

const res = Object.entries(people).forEach(([name, {weight}])=>{
  console.log(name, weight);
});

You can't. Jerry,Malcom, and Bob are just the variable names, you have two obvious solutions:

Add a name attribute to your objects.

var jerry = {
 name: "jerry",
 weight: 178
}

Or change your array to an object, and use the key as the name of your object.

var people = {jerry: jerry, malcom: Malcom, bob: Bob}

For example:

var jerry = {
  weight: 178
}

var Malcom = {
  weight: 178
}

var Bob = {
  weight: 178
}

var people = {jerry: jerry, malcom: Malcom, bob: Bob}

for(var person in people){
  if(people.hasOwnProperty(person)){
    console.log(person, people[person].weight);
  }
}
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
-3

var Some = {
  MyValue : 1234
}
for (var i in Some) console.log(i);

var people = {
 jerry : { weight: 178 },
 Malcom : { weight: 220 },
 Bob : { weight: 134 }
}

for (var i in people) console.log( i +' : '+ people[i].weight )
MypKOT-1992
  • 191
  • 3