Delete field from JSON file in node - javascript

I want to delete a field from a JSON file in node. Suppose my file looks like this
{
'name': John Doe,
'nickname': Johnny
}
and if I say delete('nickname'); I want it to look like this.
{
'name': John Doe
}
How should I go about doing this? Also is there a way to check how many elements are left in the file? And if so how could I delete the whole file if it is empty?
update: this is the code I'm debugging
var data = require(pathToFile);
var element = data[deleteKey];
delete element;
fs.writeFileSync(pathToFile, JSON.stringify(data, null, 4), 'utf8');
res.end(deleteKey + ' was deleted');
console.log(JSON.stringify(data, null, 4));

To check how many elements are left in the JSON file, you can use this:
Object.keys(jsonArray).length;
To delete an element however:
var json =
{
'name': John Doe,
'nickname': Johnny
}
var key = "name";
delete json[key];
As for deleting a file, you can use ajax and call a server-side file to accomplish this.

You can just delete it...
var myObj = { 'name': 'John Doe', 'nickname': 'Johnny'};
delete myObj.nickname;
OR
var myObj = { 'name': 'John Doe', 'nickname': 'Johnny' };
delete myObj["nickname"];
OUTPUT
{name: "John Doe"}

Related

Working with list of arrays and accesing its elements in React

I'm using two objects in my app.
First type looks like this:
and I can access the gender like this: data.results[0].gender
So to elaborate on this i decided to record all people in the data array and now i have an object that looks like this:
how do I reference and access names of selected people from an object like this?
Thanks
To be fair, this seems like a poor/messy way to keep data in general, but maybe you could define a map between your people's ids or uuids or usernames, let's say, and the corresponding objects and then call them by their ids to retrieve the info you need on them:
const peopleMap = new Map();
for (person in array){
peopleMap.set(person.id.value, person)
}
ex.
let aparticularid = '92bd-asd1-24nas-213c-3cac-31ac';
let person = peopleMap.get(aparticularid);
let fullname = person.title + ' ' + person.first + ' '+ person.last;
Realistically you'd retrieve the particular id from elsewhere or some event. Or you can map names to the corresponding objects if you can guarantee their uniqueness(if they are not unique, the objects will be overridden in the map)
You can use .map() to iterate over the items of an Array.
Example -
yourArray.map(x => {
const {title, first, last} = x.name;
console.log(`${title} | ${first} } ${last}`)
})
const yourArray = [
{
id: {name: 'HETU', value: 'NAANANFSF'},
name: {title: 'Ms.', first: 'Mila', last: 'Heitet'}
},
{
id: {name: 'Tom', value: 'TANN'},
name: {title: 'Mr.', first: 'Tom', last: 'Altar'}
},
{
id: {name: 'HARRY', value: 'HARSFF'},
name: {title: 'Mr.', first: 'Harry', last: 'Krishna'}
}
];
yourArray.map(x => {
const {title, first, last} = x.name;
console.log(`${title} | ${first} | ${last}`)
})
Based on the second screenshot, this is an array of objects. Lets call the array arr then you can access the name of the i-th person in the following way:
arr[i].name.first and arr[i].name.last respectively.

Storing associative data by ID

I've got a lot of (user) objects which come from a socket. On every new connection I get a new user object, but on every disconnect I just got the ID of the recently disconnected user.
What's the best way to store these user objects client-side?
Already tried something like this (pseudo code without sockets and just for testing)
var connectedUsers = [];
connectedUsers[12] = {
id: 12,
name: "Test",
// ...
};
connectedUsers[29] = {
id: 29,
name: "Test 2"
};
Kinda works - but now I've got an array with lots of empty spaces. The upside is that it would be easy to remove a user just by his ID.
Using an object to store the objects probably won't be the right choice, since I don't have numeric indexes.
Use an object. The former indices are converted to strings and taken as properties for the object.
var connectedUsers = {};
Working example:
var connectedUsers = {};
connectedUsers[12] = { id: 12, name: "Test", };
connectedUsers[29] = { id: 29, name: "Test 2" };
document.write('<pre>' + JSON.stringify(connectedUsers, 0, 4) + '</pre>');

JSON.stringify set root element

I want to convert my object into a JSON String where the root element should be the name of my object.
var data = {
name: 'qwertz',
age: 23,
skills: [
'html', 'css'
]
}
var json = JSON.stringify(data);
The output is:
{"name":"qwertz","age":23,"skills":["html","css"]}
But I want this:
{"data":{"name":"qwertz","age":23,"skills":["html","css"]}}
Can someone give me a hint how to reach this? Thanks you :)
As simple as that:
var json = JSON.stringify({ data: data });
Try this
JSON.stringify({'data':data})

Adding to a JSON string

I have a JSON string as follows:
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
It is generated after calling this function in KnockOut:
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
TypeName: line.category().TypeName,
TypeID: line.category().TypeID
: undefined
});
alert(JSON.stringify(dataToSave));
However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:
{
"Name":"Mark",
"Email":"me#me.com",
"Tel":"0123456789",
"Rooms":
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
}
Is there a proper way of adding this information to the JSON, or is it just as simple as:
var toSend = "{\"Name\":\"Mark\":\"Email\":\"me#me.com\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}";
Thank you,
Mark
Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.
Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?
var toSend = JSON.stringify({
Name: "Mark",
Email: "me#me.com",
Tel: "0123456789",
Rooms: dataToSave
});

Json, displaying the usernames

Using
var arrayOfObjects = eval(photo.likes.data);
var objects = arrayOfObjects;
console.log(objects);
I get the code below is what console.log echos
json
[
Object
full_name: "marcab12"
id: "181407552"
profile_picture: "http://images.instagram.com/profiles/profile_181407550_75sq_1339521398.jpg"
username: "marcab12"
__proto__: Object
,
Object
full_name: "Ramage1992"
id: "21574723"
profile_picture: "http://images.instagram.com/profiles/profile_21574703_75sq_1349343851.jpg"
username: "ramage_1992"
__proto__: Object
]
How can I manage to show just the usernames on two lines as the javascipt I use seems to echo the 2 objects.
EDIT
$.each(likesperimage,function(index){
liked = likesperimage[index].username;
console.log(photo.id+' - '+liked);
});
I am assuming that this is a json array and you want to display the username for all the users in this array.The following code should work
$.each(arrayOfObjects,function(index)
{
console.log(arrayOfObjects[index].username);
});
here is the link to each in jquery api
http://api.jquery.com/jQuery.each/
Please test this code before using it.This is just a demonstration of how it can be done and there might be better ways to do it.

Categories

Resources