简体   繁体   中英

Remove/Update JSON key in node.js

I am trying to either update or remove (and then rewrite) a JSON key in node.js

JSON:

{"users":[{"Discordid":"discid","Username":"user","Password":"pass","School":"schoolname"}, {"Discordid":"discid1","Username":"user1","Password":"pass1","School":"schoolname1"}]}

I want to remove the entire {"Discordid":"discid","Username":"user","Password":"pass","School":"schoolname"} via a for loop so I make use of variable a which equals the number in which the data is I want to delete.

I have tried:

fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {
     if (err) throw err
     var magistercreds = JSON.parse(data1)
     for (a = 0; a < Object.keys(magistercreds.users).length; a++) delete magistercreds.users[a]

And other things which all did not work.

fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {
     if (err) throw err
     var magistercreds = JSON.parse(data1)
     for (a = 0; a < magistercreds.users.length; a++){
          magistercreds.users.splice( a, 1 );
          a--; // to step back, as we removed an item, and indexes are shifted
     }

But may be you want just update, so you can make it simple:

fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {
     if (err) throw err
     var magistercreds = JSON.parse(data1)
     magistercreds.users[68468] = {.....}

The question isn't clear on whether a key is to be removed or an entire object. Assuming an entire element is to be removed from the array users , the splice method can be used.

First find the index of the element you want to remove using findIndex . Then you can use splice to modify the array in-place.

Sample:

fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {
     if (err) throw err
     var magistercreds = JSON.parse(data1)
     // Assuming you want to delete the element which has the Discordid property as "discid"
     var indexOfElement = magistercreds.findIndex(el => el.Discordid === "discid")
     magistercreds.users.splice(indexOfElement, 1) // This will remove 1 element from the index "indexOfElement" 
}

To add on, using Object.keys to iterate over an array is not necessary. The for loop in the original question can be rewritten as:

for (a = 0; a < magistercreds.users.length; a++) delete magistercreds.users[a]

Please edit the question to add more information if this is not what you were looking to achieve.

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