JavaScript数据对象在条件检查中被填充,但特定对象变量的次要输出未定义。

huangapple go评论74阅读模式
英文:

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));

JavaScript数据对象在条件检查中被填充,但特定对象变量的次要输出未定义。

JavaScript数据对象在条件检查中被填充,但特定对象变量的次要输出未定义。

答案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);
		}
	}
});

huangapple
  • 本文由 发表于 2023年5月25日 04:47:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定