如何获取对象的名称

时间:2016-05-08 13:24:00

标签: javascript jquery object

var myobj =
{
test1 : {name1 : "" , name2 : ""},
test2 : {name1 : "" , name2 : ""},
test3 : {name1 : "" , name2 : ""}
}

console.log(myobj) , response ===> Object {test1: Object, test2: Object, test3: Object}

如何获取对象的名称...我希望这是

response === > myobj (name of objet)

这可能吗?

1 个答案:

答案 0 :(得分:0)

对象没有名称。 (例如)test1中的所有内容是带有名称的属性,其值为对象引用。

您可以使用for-inObject.keys(myobj).forEach循环遍历对象的可枚举属性名称:

var name;
for (name in myobj) {
    console.log(name + ".name1 = " + myobj[name].name1);
}

Object.keys(myObj).forEach(function(name) {
    console.log(name + ".name1 = " + myobj[name].name1);
});

for-in直播示例:

var myobj =  {
  test1 : {name1 : "Joe" , name2 : ""},
  test2 : {name1 : "Linda" , name2 : ""},
  test3 : {name1 : "Pashtel" , name2 : ""}
};
var name;
for (name in myobj) {
  snippet.log(name + ".name1 = " + myobj[name].name1);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Object.keys(...).forEach直播示例:

var myobj =  {
  test1 : {name1 : "Joe" , name2 : ""},
  test2 : {name1 : "Linda" , name2 : ""},
  test3 : {name1 : "Pashtel" , name2 : ""}
};
Object.keys(myobj).forEach(function(name) {
  snippet.log(name + ".name1 = " + myobj[name].name1);
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>