Reputation: 119
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);
})
Upvotes: 0
Views: 1263
Reputation: 693
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);
})
Upvotes: 2
Reputation: 568
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)
})
Upvotes: 0