简体   繁体   English

使用nodejs添加对象数组并在file.txt上读取

[英]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 在我使用节点的文件中,我可以读取这些对象,并且我希望这些对象成为数组,所以我使用了.split('\\n')问题是如果我尝试将其作为字符串获取,

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

i got undefined undefined

thats how i write the objects on my file.txt 多数民众赞成我如何在我的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 JSON字符串应为'{“ key”:“ value”}'格式

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! 通过使用\\n分割文件,您将获得一个有效且可迭代的数组,但是您可能需要考虑的是objectArray每个条目都是一个字符串,而不是一个对象! So you need to make it an object, by using JSON.parse , before you access its properties. 因此,在访问其属性之前,需要使用JSON.parse将其设为对象。 Thus your final code will be as follows. 因此,您的最终代码如下。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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