[英]Form created dynamically from Javascript Object loop. How to save data back to object
[英]Object created from a loop in JavaScript, how to analyse them in a json
我是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);
}
使test
成為一個數組並將cam
對象push()
。 還為XAddrs值定義一個數組。
var test = [];
var xaddrs = [];
// your other code
...
onvif.Discovery.on('device', function(cam,rinfo,xml){
// function will be called as soon as NVT responses
nombrecamera+=1;
console.log(cam);
// push cam object into array
test.push(cam);
cam2= JSON.stringify({cam}, null , ' ');
//console.log(cam2);
STREAM.write(cam2);
console.log(test);
});
然后提取XAddrs
並將其推入xaddrs
數組。
function extract() {
test.forEach(cam => {
xaddrs.push(cam.probeMatches.probeMatch.XAddrs);
});
// now you have an array containing only the XAddrs elements
console.log(xaddrs);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.