turtlepower
turtlepower

Reputation: 758

Pushing new data into a multi-dimension array

I have an arrary:

[ { id: 'XXXXXXXXXX',
    message:
     'XXXXXXXXXX',
    createdTime: 'XXXXXXXXXX',
    fullPicture:
     'XXXXXXXXXX',
    reactions: 6,
    comments: 0,
    shares: 0 },
  { id: 'XXXXXXXXXX',
    message:
     'XXXXXXXXXX',
    createdTime: 'XXXXXXXXXX',
    fullPicture:
     'XXXXXXXXXX',
    reactions: 50,
    comments: 4,
    shares: 6 } ]

I want to to push a new variable in each of the dimensions - called reach.

I've tried doing a loop looking something like:

for(a=0; a<array.length; a++){
array[a].push("Hello": "World")
}

However, this doesn't seem to be working - is this the right way to be pushing in data?

Upvotes: 0

Views: 45

Answers (1)

Snow
Snow

Reputation: 4097

You have an array of objects, so you should be assigning to an object property, rather than push:

for(let a=0; a<array.length; a++){
  array[a].Hello = "World";
}

You can only call push on an array.

It might be clearer with a forEach loop, which would require you to name the variable:

array.forEach((obj) => {
  obj.hello = 'World';
});

Upvotes: 5

Related Questions