Home > Software design >  How to push an item to the array inside JSON Object?
How to push an item to the array inside JSON Object?

Time:11-08

I am trying to make inventory functionality using Discord.js and struggling on how to push an item to the array inside JSON Object. Inside the JSON, every user with unique 'userID' has their own array 'inventory'.

The thing I want to achieve is: After user types 'get' command in the chat, the item is pushed to the inventory array and the JSON file is updated.

.json file:

{
    "userID": {
        "inventory": []
    }
}

.js file:

const item = itemName

inventory[userID] = {
    inventory: inventory[userID].inventory   item,
}
fs.writeFile('./data/inventory.json', JSON.stringify(inventory), err => {
    if (err) console.log(err)
})

Output (after using command twice):

{
    "userID": {
        "inventory": ["itemNameitemName"]
    }
}

Expected output (after using command twice):

{
    "userID": {
        "inventory": ["itemName", "itemName"]
    }
}

The thing I want to achieve is: After user types 'get' command in the chat, the item is pushed to the inventory array and the JSON file is updated. I suppose I need to use .push() somewhere, but I tried it million times in all configurations I could think of and it always throws an error, that .push() is not a function.

CodePudding user response:

Instead of making a new object for the user every time you want to update the inventory, it would be much easier if you can just push the item to the inventory instead of reassigning. @DanielAWhite wrote the correct solution but I think you misunderstood where to put that particular piece of code. What you might have tried is this:

const inventory = {
  "userID": {
    "inventory": ["testOne"]
  }
}

const item = "test"
const userID = "userID"

inventory[userID] = {
  inventory: inventory[userID].inventory.push(item),
}
console.log(inventory)

Instead, what the correct way was to do away with the inventory[userID] = {} part and just directly push the item to the inventory by doing this:

const inventory = {
  "userID": {
    "inventory": ["testOne"]
  }
}

const item = "test"
const userID = "userID"

inventory[userID].inventory.push(item)
console.log(inventory)

(Note: I edited the code a little bit so that you could try to run this code right here, but this should work with your fs.writeFile as well

CodePudding user response:

Try this :

let rawdata = fs.readFileSync('inventory.json');
let inventory = JSON.parse(rawdata);
inventory["userID"] = {
    inventory: [...inventory["userID"].inventory, item],
}
fs.writeFile('./inventory.json', JSON.stringify(inventory), err => {
    if (err) console.log(err)
})
  • Related