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)
这可能吗?
答案 0 :(得分:0)
对象没有名称。 (例如)test1
中的所有内容是带有名称的属性,其值为对象引用。
您可以使用for-in
或Object.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>