Search code examples
reactjssetstatereact-state-managementnested-object

How to insert object into list of objects in react?


I have list of nested objects as:

          this.state = {
              
           lst: [
            {
                id: "TKT4321",
                subject: "abc",
                reply: [
                    { id: "TKT34343", subject: "axyz" },
                ]
            },
            {
                id: "TKT34341",
                subject: "aaaaa",
                reply: [
                    { id: "TKT322", subject: "abfjf" },
                ]
            },                
        ],            
    }

I want to append object to reply property . e.g

           {
                id: "TKT34341",
                subject: "aaaaa",
                reply: [
                    { id: "TKT322", subject: "abfjf" },
                    { id: "TK2222", subject: "jkjk" },
                ]
            },

Which is the best way to do it ? Please help me .


Solution

  • Ciao, here working example:

    let lst = [
                {
                    id: "TKT4321",
                    subject: "abc",
                    reply: [
                        { id: "TKT34343", subject: "axyz" },
                    ]
                },
                {
                    id: "TKT34341",
                    subject: "aaaaa",
                    reply: [
                        { id: "TKT322", subject: "abfjf" },
                    ]
                },                
            ];
            
            let result = lst.map(el => {
               if (el.id === "TKT34341"){
                   el.reply.push({ id: "TK2222", subject: "jkjk" });
               }
               return el;
            });
            
            console.log(result);
            
      

    Then if you want to store result into state, just call this.setState({lst : result});