mihailmul
mihailmul

Reputation: 27

JavaScript: How to reference an array inside an object inside an array and push something to it?

I have the following array:

var ships = [ { locations: [], hits:0 },
              { different: [], different1:0 },
              { different3: [], different2:0 } ];

How do I reference the array "locations" inside the 1st object and push something to it? Thanks!

Upvotes: 0

Views: 54

Answers (2)

SaiKD
SaiKD

Reputation: 72

It should be

ships[0].locations.push(newItem);

Upvotes: 0

Ele
Ele

Reputation: 33726

You can use index access or Destructuring assignment

Index access

var ships = [ { locations: [], hits:0 },
              { different: [], different1:0 },
              { different3: [], different2:0 } ];
              
ships[0].locations.push("Ele from SO");

console.log(ships)

Destructuring assignment

var ships = [ { locations: [], hits:0 },
              { different: [], different1:0 },
              { different3: [], different2:0 } ];
              
var [obj] = ships;
obj.locations.push("Ele from SO");

console.log(ships)

Upvotes: 1

Related Questions