[英]How to join/split objects that are one object in fact
var ipRegex = require('ip-port-regex');
...
for(var i = 0; i < orgArrayWithHostsAndPorts.length; i++) {
ipPort = ipRegex.parts(orgArrayWithHostsAndPorts[i]);
console.log(ipPort);
/*
Gives long listing
{ ip: 'firstip', port: 'firstport' }
{ ip: 'secondip', port: 'secondport' }
*/
fs.writeFileSync('/tmp/test.json', JSON.stringify(ipPort, null, 2), 'utf-8');
}
所以當我做fs.writeFileSync
我只看到第一個對象。 我真正想要的是將每個 ip/port 屬性保存為數組中單獨對象的集合。 我無法將,
添加到每個對象
fs.writeFileSync
方法將在每次調用時覆蓋文件。 由於您對列表中的每個項目都調用一次,因此文件中同時只有一個項目。
此外,使用fs.appendFileSync
會寫入所有對象,使您的文件看起來像:
{ "ip": "firstip", "port": "firstport" }
{ "ip": "secondip", "port": "secondport" }
但這不是有效的 .json。 這些對象必須包含在一個數組中並用逗號分隔:
[
{ "ip": "firstip", "port": "firstport" },
{ "ip": "secondip", "port": "secondport" }
]
我能想到的獲得您想要的結果的最簡單方法是將您的數據映射到一個新數組中,然后將該數組寫入文件:
ipPorts = orgArrayWithHostsAndPorts.map( data => ipRegex.parts(data));
fs.writeFileSync('/tmp/test.json', JSON.stringify(ipPorts, null, 2), 'utf-8');
該文件以寫入模式打開,因此您在每次執行 for 循環時都會覆蓋。 更好的方法是以追加模式打開文件並寫入內容。 看看如何附加到節點中的文件?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.