0

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!

3
  • ships[0].locations.push(foobar) Commented Mar 13, 2018 at 19:57
  • 2
    this will be a good read for you developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Mar 13, 2018 at 19:59
  • @mihailm it would help us more if you shared more of your code. Are you looping over ships? Commented Mar 13, 2018 at 20:03

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

It should be

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

1 Comment

A little explanation to the original poster (and future readers) is always going to make your answers better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.