1

I would like to push to a single object similar to the following code

error = [];
error.push({name: 'Name is too short'});
error.push({email: 'Email address is too short'});

The problem with this is that it makes multiple objects and I wish to only create one.

Can you tell me the best way to do this or point me in the right direction, thank you.

dcdcdc
  • 253
  • 3
  • 12

4 Answers4

2

You don't push to an object, just make it an object and not an array and add properties:

var error = {};
error.name = 'Name is too short';
error.email = 'Email address is too short';
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
1

Remember, your JSON syntax. You are pushing everything to an array in your example. You don't want to "push" anything here but instead append properties to an existing object:

var error = {};
error.name = 'Name is too short';
error.email = 'Email address is too short';
KJ Price
  • 5,774
  • 3
  • 21
  • 34
  • I assumed OP wanted to keep his array setup, but this is probably what he really wants. –  Mar 04 '15 at 19:57
0

You can just add things to the object after adding it to the array:

error[0].email = "Email address is too short";
0

If you are using JQuery you can use

var object = $.extends({name: 'Name is too short'}, {email: 'Email address is too short'});

If you are not using JQuery, Ryan Lynch provide a solution here.

Community
  • 1
  • 1