How to add an object to an array of object?


#1

Hi everyone!

First of all… let me show you my model:

player
   |-nickname
   |-date
   |-inventory (array)
       |- object_name
       |- price
       |- color

Well, so i’m newbie at this subject and I dont know how to add an item into the array of item (it’s ‘Inventory’), and inventory belongs to a player, obviously. How it’s the method? don’t know if I need to use a subscribe or a observable also…

Thank you very much

Regards

UPDATED:
I did that code, but doesn’t work, what should I do?

addItem(item: Item, player: Player) {
    if (item) {
      player.inventory.push(item)
      this.provider.editPlayer(player)
      this.toast.show(`Se ha añadido el item al player ${player.inventory}`)
      this.navCtrl.setRoot('HomePage')
    }
  };

UPDATED2

Interfaces:

export interface Player {
    key?: string;
    nickname: string;
    color: string;
    hair: string;
    Inventory?: Item[];
}

export interface Item {
    key?: string;
    name: string;
    color: string;
    price: number;
    durabilidad: string;
    size: number;
}

#2

hello,

have you made an interface for player? Yes, then please show it, because a correct interface should help with that, because it shows an error if there is something wrong, Maybe inventory should not be an array and should be itself defined as interface.

Best regards, anna-liebt


#3

deleted. here was bullshit written. I go to bed an take a look tomorrow.

Sorry ana-liebt


#4

What does editPlayer do?


#5
    private listPlayerRef = this.db.list<Player>('players');

    editPlayer(player: Player) {
        return this.listPlayerRef.update(player.key, player);
    }

#6

This is turning into a matryoshka. It is going to be hard for anybody to help you without seeing something minimal and complete.


#7

Hello,

late again.
Please try Inventory without ? optional. If you get an error, please post it.

Best regards, anna-liebt


#8

Do not hesitate to ask me for more information to resolve the problem, thank you very much, could you give me an example about how to add an item to an array of object (array of ‘Item’ object) ??¿


#9

player.inventory.push(item)


#10

hello,

as you wrote or @Jacktoolsnet wrote, it seems for me that the code to push is correct syntax. So is there any error message or is checked that inventory exist or any further information or…

Best regards, anna-liebt.