我有一个具有嵌套对象和数组的对象。我正在尝试console.log
所有数据,包括嵌套对象内部的数据,但没有这样做。我得到的结果显示除对象以外的所有数据。我得到的是[Object object]
,而不是那些。我想要的是在控制台中以不是对象或JSON的格式显示所有内容(类似于下面的结果,除了我也想显示f和g的值)。
这是对象:
let data = {
a: 'Tesla',
b: 'Mclaren',
c: 'Ferrari',
d: 'Lamborghini',
e: 'Lotus',
'f':{
name: 'John',
'e-mail': '[email protected]',
phone: '+12345678',
country: 'USA',
car: 'Toyota Prius'
},
'g':{
name: 'Sophie',
'e-mail': '[email protected]',
phone: '+12345678',
country: 'UK',
car: 'Nissan Bluebird'
},
h: 'Volkswagen',
i: 'Bugatti',
j:[
'% mileage',
'% top speed',
'% suspension',
'% navigation',
'% horsepower',
'% 0-60s'
]
}
这是我尝试的代码:
for(var key in data){
console.log(key + " : " + data[key]);
}
这是我得到的结果:
a : Tesla
b : Mclaren
c : Ferrari
d : Lamborghini
e : Lotus
f : [object Object]
g : [object Object]
h : Volkswagen
i : Bugatti
j : % mileage,% top speed,% suspension,% navigation,% horsepower,% 0-60s
let data = {
a: 'Tesla',
b: 'Mclaren',
c: 'Ferrari',
d: 'Lamborghini',
e: 'Lotus',
'f':{
name: 'John',
'e-mail': '[email protected]',
phone: '+12345678',
country: 'USA',
car: 'Toyota Prius'
},
'g':{
name: 'Sophie',
'e-mail': '[email protected]',
phone: '+12345678',
country: 'UK',
car: 'Nissan Bluebird'
},
h: 'Volkswagen',
i: 'Bugatti',
j:[
'% mileage',
'% top speed',
'% suspension',
'% navigation',
'% horsepower',
'% 0-60s'
]
}
for(var key in data){
console.log(key + ": ", data[key]);
}
console.log(JSON.parse(JSON.stringify(data)))
:
console.log(JSON.parse(JSON.stringify(data)))
,Chrome和Firefox至少会将reference记录到一个对象中。 console.log(obj)
会将您的对象转换为不是对象的JSON。 console.log(JSON.stringify(obj))
会将JSON转换回一个对象,作为一个单独的,不会改变的独立引用。
console.log(JSON.parse(JSON.stringify(obj)))
您可以使用:
let data = {
a: 'Tesla',
b: 'Mclaren',
c: 'Ferrari',
d: 'Lamborghini',
e: 'Lotus',
'f':{
name: 'John',
'e-mail': '[email protected]',
phone: '+12345678',
country: 'USA',
car: 'Toyota Prius'
},
'g':{
name: 'Sophie',
'e-mail': '[email protected]',
phone: '+12345678',
country: 'UK',
car: 'Nissan Bluebird'
},
h: 'Volkswagen',
i: 'Bugatti',
j:[
'% mileage',
'% top speed',
'% suspension',
'% navigation',
'% horsepower',
'% 0-60s'
]
};
console.log(JSON.parse(JSON.stringify(data)));
OR
console.log(JSON.stringify(data));
如果您在节点环境中,则可以使用util模块中的inspect方法:console.log(data);
https://nodejs.org/api/util.html#util_util_inspect_object_showhidden_depth_colors
您也可以像上面一样通过将最后一个参数设置为true来使其带有颜色记录!
如果您在浏览器环境中,仍可以使用util模块,但必须使用捆绑程序,例如webpack或browserify。
如果您不在乎输出格式const util = require('util');
console.log(util.inspect(bigObject, false, null, true)) ;
应该可以正常工作
如果迭代包含对象实例的对象,则将其记录为引用。如果要迭代,则在迭代时使用typeof将对象扔到对象中。如果它是对象,则迭代内部对象。