简体   繁体   中英

How to print each object of an array of objects in a new line in txt file using javascript?

My result set is an array of objects that returns from a function.

[{brand:"Toyota", model: "Prius"}, {brand:"Subaru", model:"WRX"}, {brand:"Honda", model: "Accord"}]

I am writing it into a file using

fs.writeFile('test.txt', array, (err) => {
    if (err) {
        console.log(err);
    }
})

The "text.txt" looks like this:

[{brand:"Toyota", model: "Prius"},{brand:"Subaru", model:"WRX"},{brand:"Honda", model: "Accord"}]

How could i print them in format like this:

{brand:"Toyota", model: "Prius"}
{brand:"Subaru", model:"WRX"}
{brand:"Honda", model: "Accord"}

You can try passing a function

let arr = [{brand:"Toyota", model: "Prius"}, {brand:"Subaru", model:"WRX"}, {brand:"Honda", model: "Accord"}];

function mapLine(_arr, i){
  let a = [];
  _arr.forEach((item)=>{
    newLine = i === 0 ? "" : "\r\n";
    a.push(newLine + JSON.stringify(item));
  })
  return a;
}

fs.writeFile('test.txt', mapLine(arr), (err) => {
    if (err) {
        console.log(err);
    }
})

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