-1

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!

unaid
  • 1
  • 1
  • 1
    Does this answer your question? [How to append something to an array?](https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array) – Lucas Henrique Feb 16 '21 at 21:51

1 Answers1

0

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.

technikfe
  • 121
  • 1
  • 8