简体   繁体   中英

adding object array with nodejs and read it on file.txt

lets say i have these objects

{name:'somename',date:'10/20'}
{name:'anothername',date:'07/30'}

in my file using node i can read these objects and i want these to to be an array so i used .split('\\n') the problem is i get it as a string means if i try to

objectArray.map((singleObject)=>{
console.log(singleObject.name)
})

i got undefined

thats how i write the objects on my file.txt

fs.appendFile(path.join(__dirname,'file.txt'),
        object,(e)=>{
            console.log(e);
    })

尝试按以下方式访问

console.log(singleObject["name"])

JSON string should be in '{"key":"value"}' format

so you should write it in required format.

fs.appendFile(path.join(__dirname,'file.txt'),
    JSON.stringify(object),(e)=>{
        console.log(e);
});

after read file, parse data.

fs.readFile('file.txt','utf8',function(err,data){
   data = data.split("\n");
   var a = JSON.parse(data[0]);
   console.log(a);
})

By splitting your file using \\n , you have a valid and iterable array, but what you may need to considered about is that each entry of objectArray is a string, not an object! So you need to make it an object, by using JSON.parse , before you access its properties. Thus your final code will be as follows.

objectArray.map((singleObject) => {
    let obj = JSON.parse(singleObject)
    console.log(obj.name)
})

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