在javascript中,我有一个对象数组。如何控制日志记录对象的名称,而不是内容?

时间:2017-03-14 21:51:46

标签: javascript arrays console.log

jerry = {
  weight: 178

}

Malcom = {
  weight: 220
}

Bob = {
  Weight: 134

}

people = [jerry, Malcom, Bob]

console.log(people[0]);

我正在尝试获取对象名称的console.log,“jerry”。感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

ES6版本:使用Object#entriesArray#forEachdestructuring

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);
});

你做不到。 Jerry,Malcom和Bob只是变量名,你有两个明显的解决方案:

为对象添加name属性。

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

或者将数组更改为对象,并使用该键作为对象的名称。

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

例如:

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);
  }
}

答案 1 :(得分:-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 )