gpt4 book ai didi

javascript - 从 JavaScript 中的循环创建的对象,如何在 json 中分析它们

转载 作者:行者123 更新时间:2023-11-29 10:58:56 24 4
gpt4 key购买 nike

我是 Javascript 的初学者,我需要分析在循环中生成的 JavaScript 对象以保留一个参数并为循环中生成的所有对象保存此参数。

这是我的程序

var onvif = require('onvif');
var fs = require('fs');

var nombrecamera=0;
var taille=0;
var test ='';

function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}

var STREAM = fs.createWriteStream('STREAM.txt',{flags:'r+'});

onvif.Discovery.on('device', function(cam,rinfo,xml){
// function will be called as soon as NVT responses
nombrecamera+=1;
console.log(cam);
test += cam;
cam2= JSON.stringify({cam}, null , ' ');
//console.log(cam2);
STREAM.write(cam2);
console.log(test);
});

onvif.Discovery.probe({timeout:1000,resolve:false});

在我的示例的输出中,我得到了其中的 4 个:

{ probeMatches:
{ probeMatch:
{ endpointReference: [Object],
types: 'tdn:NetworkVideoTransmitter',
scopes: ' onvif://www.onvif.org/type/video_encoder onvif://www.onvif.org/location/country/china onvif://www.onvif.org/type/network_video_transmitter onvif://www.onvif.org/hardware/IPC-122 onvif://www.onvif.org/Profile/Streaming onvif://www.onvif.org/name/IPC-BO',
XAddrs: 'http://192.168.1.81:10004/onvif/device_service',
metadataVersion: 1
}
}
}

我只想保留生成的所有对象的 XAddrs,然后将它们放入 json 中。

我的第一个想法是将这个对象字符串化,然后创建一个可写流并将所有 json 放在一起,但在这种情况下,json 之间没有逗号,因此它不会创建包含整个数据的大 json。

谢谢你的帮助

朱尔斯

最佳答案

了解您有多少个地址的最简单方法是数组的.length 函数。

由于我不知道您是否需要一个具有唯一地址的列表,或者同一个地址可能会出现多次,所以我将向您展示这两种解决方案。

仅限唯一地址

function extract() {
test.forEach(cam => {
const deviceAddress = cam.probeMatches.probeMatch.XAddrs;

// only if the xaddrs is not in list yet, add it
if(test.filter(xad => xad === deviceAddress).length <= 0) {
xaddrs.push(cam.probeMatches.probeMatch.XAddrs);
}
});

// show the number of addresses
const listCount = xaddrs.length;
console.log('listCount: ', listCount);
}

没有唯一地址

function extract() {
test.forEach(cam => {
xaddrs.push(cam.probeMatches.probeMatch.XAddrs);
});

// show the number of addresses
const listCount = xaddrs.length;
console.log('listCount: ', listCount);
}

关于javascript - 从 JavaScript 中的循环创建的对象,如何在 json 中分析它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51124105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com