Jump to content

How to Push an Empty Array into an Object


Go to solution Solved by gizmola,

Recommended Posts

I have an object that contains arrays and other elements. I need to add an array to that object but I cannot figure out how to do that. This is what I tried:


Can someone give me the correct syntax? TIA.

Link to comment
Share on other sites

Is json_array a JSON string or an array? Assuming it's an Array object, I'd say drop the square brackets from excludes (I'm assuming excludes is a valid Array object as well). Also, realize that Array.push() returns the resulting array, so if you're not assigning the return to anything you clearly won't see the updated values.

Are you getting any errors in your console? What does the code around this look like? There's not really enough here to say with any certainty what issue(s) you're having.

Link to comment
Share on other sites

the push method is for an array.  

Adding to objects can be done in a few ways: 

  • Using array syntax:  obj['property']
  • Using "." notation:  obj.property
obj = { 
  'foo': ['apple', 'banana'],
  'getFoo': function() {
     return this.foo


obj['bar'] = ['red', 'green']

obj.foobar = function() {
  return this.foo.concat(this.bar)


Example code in this codepen.



Link to comment
Share on other sites

  • Solution
1 hour ago, gw1500se said:

To clarify, 'excludes' is not in the object (yes it is a json array/object) at this point but I want it to be an empty array for future use:

json_array.excludes.push(<some string>);


And everything I wrote previously still applies.

let json_array = {}
json_array.excludes = []

// Use array method

//array syntax



I Updated the codepen as well with this example code.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.