英文:
Javascript data object is populated in a conditional check, but secondary output of specific object variables are undefined?
问题
我知道这是一些奇怪的异步问题,但我应该如何输出 "nid" 值?我制作了一个条件语句来检查 "data" 是否已填充,它确实包含一些内容。因此,在下一个语句中,我只想输出内部对象变量,如 "nid"。我知道这与异步有关,但我只想输出我需要的变量。
console.log(JSON.stringify(data.nid));
英文:
I know this is some weird async issue, but how would I output the "nid" value? I made a conditional statement to check if "data" is populated it does indeed contain something. So in the next statement I just want to output the internal object variables such as "nid". I know its something to do with async, but I just want to output the variable I need.
Stop linking me to other "duplicate" questions or answers as the solution below does not work as shown in other questions!
console.log(JSON.stringify(data.nid));
答案1
得分: 2
根据您的屏幕截图和data
的输出,例如:
["nid":[{"value":334}],...
您实际接收到的数据是一个字符串,不是一个对象。因此,当然 data
没有.nid
属性。
您需要先将字符串解析为一个对象。正如@CherryDT所指出的,您可能最终会尝试解析一个不完整的字符串。因此,如果您真的想在数据事件处理程序中记录数据,请将解析包装在try-catch块中。
response.on('data', (chunk) => {
data += chunk;
let tempData;
if (data) {
let error = false;
try {
tempData = JSON.parse(data);
} catch (err) {
error = true;
}
if (!error) {
console.log(tempData.nid);
}
}
});
英文:
Based on your screenshot and the output of data
e.g.
["nid":[{"value":334}],...
the actual data you are receiving is a string and not an object. As such data
of course does not have a .nid
property.
You need to parse the string to an object first. As @CherryDT pointed out though you might end up trying to parse an incomplete string. So if you really want to log the data inside the data event handler, wrap the parsing inside a try-catch block.
response.on('data', (chunk) => {
data += chunk;
let tempData;
if (data) {
let error = false;
try {
tempData = JSON.parse(data);
} catch (err) {
error = true;
}
if (!error) {
console.log(tempData.nid);
}
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论