How to add a new object to another within an array

I have an array which looks like this:

array = [
         {code1: 
          {
           number: 2,
           name: "e"
          }
         },
         {code2: 
          {
           number:2,
           name: "u"
          }
         }
         ]

and I want to add the following as a new object to say "code1" without changing the data it now has.

{
number: 3,
name: "j"
}

how can I do it? Thank you!

23 thoughts on “How to add a new object to another within an array”

  1. 1st approach

    If I understood what you want to do correctly this could work:

    array = [
             {code1: 
              {
               number: 2,
               name: "e"
              }
             },
             {code2: 
              {
               number:2,
               name: "u"
              }
             },
         {code1:
          {
           number: 3,
           name: "j"
          }
         }
        ];
    

    2nd approach

    However this would make the structure more difficult to traverse. As an alternative you could make the whole thing into a dictionary of arrays, like this:˛

    let object = {//doesn't matter what we call it
        code1:[
          {
               number:2,
               name: "e"
              },
          {
               number:3,
               name: "j"
              }
        ],
        code2:[
          {
               number:2,
               name: "u"
              }
        ]
    };
    

    You’d go about accessing the new object like this: console.log(object.code1[0].number);
    You can try this approach out in the snippet bellow.

    let object = {//doesn't matter what we call it
        code1:[
          {
               number:2,
               name: "e"
              },
          {
               number:3,
               name: "j"
              }
        ],
        code2:[
          {
               number:2,
               name: "u"
              }
        ]
    };
    console.log(object.code1[0].number);

    Closing statement

    But as I’ve already said, I’m not sure if I understood your question correctly, I’d suggest editting the question to make it clearer in the future.

    Thanks for reading
    Internet person out.

    Reply

Leave a Comment