How to push an object into another object

Asked

Viewed 2,206 times

1

I have an array of objects and I’m not being able to push a certain object, example I want to push the titulo2 id but nothing I did worked out, follow the structure of the array if someone knows how to do thank

 Objt = 
  [{ titulo1:
    [
      {
        id: id
      }
    ],      
     titulo2:
    [
      {
        id: id
      }
    ]
  }] 
  • You want to add a new item next to id? id: id, outracoisa: valor

  • this when I push add another id to the object, e.g.: title1: [{id:1}, {id:2}, ...]

3 answers

3


The Objt has only 1 index [0] with 2 objects. You can make a push in the titulo2 in this way:

Objt[0].titulo2.push({id2: 'valor'});

Example:

Objt = 
  [{ titulo1:
    [
      {
        id: "id"
      }
    ],      
     titulo2:
    [
      {
        id: "id"
      }
    ]
  }]


Objt[0].titulo2.push({id2: 'valor'});
console.log(Objt[0].titulo2);

  • worked out! I was trying to do it half day, thank you very much!

1

complemented, I think his intention was to do this:

let Objt = 
  { titulo1:
    [
      {
        id: 1
      }
    ],      
    titulo2:
    [
      {
        id: 1
      }
    ]
  }
  Objt.titulo2.push ({id:2})
}
  • Note that in the question Objt is an array of objects and in its response Objt is an object with several properties.

1

 
 let objeto = [{titulo1: [ { id: 'id'} ], titulo2: [{ id: 'id' }]}];
 
 //Adicionar key ao objeto existente
 objeto[0].titulo2[0].key1 = 'teste';
 //Faz o push de um novo objeto
 objeto[0].titulo2.push({id1: 'id1'});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.