【发布时间】:2020-08-27 06:21:27
【问题描述】:
我正在尝试清理一些数据并将对象数组放置在对象内。这是我的对象数组。
职业统计:
[
{
gp: '35',
gs: '34',
mpg: '33.2',
fg: '.515',
tp: '1.5',
ft: '1.4',
rpg: '0.5',
apg: '0.7',
bpg: '.692',
spg: '0.7',
ppg: '3.6'
},
{
gp: '22',
gs: '22',
mpg: '36.7',
fg: '.504',
tp: '5.5',
ft: '2.4',
rpg: '1.7',
apg: '2.0',
bpg: '.822',
spg: '1.5',
ppg: '6.5'
},
{
gp: '57',
gs: '56',
mpg: '34.6',
fg: '.509',
tp: '3.1',
ft: '1.8',
rpg: '1.0',
apg: '1.2',
bpg: '.775',
spg: '1.0',
ppg: '4.7'
}
]
这就是我将对象的 careerStats 数组放置在玩家数组中的方式。
玩家:
player.push(
{
name: "",
image: "",
position: "",
description: "",
dob: "",
hometown: "",
country: "",
height_feet: "",
height_inches: "",
weight: "",
season: careerStats
});
这不会返回任何类型的错误;但是,当我将播放器登录到控制台时,会显示以下内容:
[
{
name: '',
image: '',
position: '',
description: '',
dob: '',
hometown: '',
country: '',
height_feet: '',
height_inches: '',
weight: '',
season: [ [Object], [Object], [Object] ]
}
]
由于我知道数据在 careerStats 数组中时很好,因此我提出了两个问题:
- 我做错了什么以接收此输出为 [ [Object], [Object], [Object] ]? ANSWER:改成console.log(JSON.stringify(player))解决
-
如果这是预期的输出并且数据确实存在,我如何将其写入显示数据的 JSON 文件而不是“[object Object]”?
JSON.stringify(player); fs.appendFile('myjsonfile.json', player, function (err) { if (err) throw err; console.log('Saved!'); });
提前感谢您的帮助!
【问题讨论】:
-
您可以点击控制台中的对象展开它们
-
试试
console.log(JSON.stringify(player))你应该会看到你所期望的。 -
console.log只会在打印泛型类型字符串之前递归到数组或对象的这么多级别。这样一来,当您只想查看一些顶级字段时,您就可以打印具有深层嵌套数据的复杂对象,而不会占用数千行。 -
@Barmar - 感谢您提供的信息,我不知道他对 console.log 的限制!
-
@Abion47 - 你也一样,今天早上我学到了一些有价值的东西。
标签: javascript node.js json