I’m having quite some trouble handling objects and storing them as JSON.
What I’m trying to do is next:
- parse json file
var links = JSON.parse([{"user1":{"username":"user1","data":"164"}},{"user2":{"username":"user2","status":0}}]);
- If user1 exists, update the whole object with new data, ELSE create new object
var key = dater['username']; //dynamic username strings
var ACCOUNT = {
username: key,
data: value,
status:1
}
if(links.hasOwnProperty(key)){
links[key] = ACCOUNT;
links=JSON.stringify(links);
fs.writeFile('status.json', links, err => {
// error checking
if(err) throw err;
console.log('Exists.. updating.');
});
}else{ // ELSE create new entry
links.push({[key]: ACCOUNT});
newData= JSON.stringify(links);
fs.writeFile('status.json', newData, err => {
// error checking
if(err) throw err;
console.log('New user.. creating');
});
}
As you can probably tell, the above doesn’t work as I’d want it to. I’m used with PHP arrays where I would simply do arrays with keys and directly update them without any ‘if/else’
Advertisement
Answer
const key = dater['username']; //dynamic username strings
const account = {
username: key,
data: value,
status: 1,
};
const matchedItem = links.find((i) => i[key]);
if (matchedItem) {
matchedItem[key] = account;
} else {
links.push({ [key]: account });
}
console.log('links:::', links);
fs.writeFile('status.json', JSON.stringify(links), (err) => {
if (err) throw err;
console.log('New user.. creating');
});