简体   繁体   中英

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

So when I do fs.writeFileSync I see only the first object. What I really want is to property save every ip/port as set of the separate objects in the array. I can't add , to every object

The fs.writeFileSync method will overwrite the file every time it's called. Since you're calling it once for every item in your list, only a single item will ever be in the file at the same time.

Additionally, using fs.appendFileSync would write all the objects making your file look like:

{ "ip": "firstip", "port": "firstport" }
{ "ip": "secondip", "port": "secondport" }

But this isn't valid .json. The objects would have to be contained in an array and separated by commas:

[
    { "ip": "firstip", "port": "firstport" },
    { "ip": "secondip", "port": "secondport" }
]

The easiest way I can think of to get the result you want is to map your data into a new array and then write that array to file:

ipPorts = orgArrayWithHostsAndPorts.map( data => ipRegex.parts(data));
fs.writeFileSync('/tmp/test.json', JSON.stringify(ipPorts, null, 2), 'utf-8');

The file is opened in write mode and hence you are overwriting on every execution of the for loop. Better way is to open the file in append mode and write the contents. Look at How to append to a file in Node?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM