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.

3
  • Why are you making error an array? Couldn't you just make it an object with multiple error keys? Commented Mar 4, 2015 at 19:55
  • error.push({name: 'Name is too short', email: 'Email address is too short'}); ? Commented Mar 4, 2015 at 19:55
  • 1
    You can have multiple attributes in one object. {name: 'name', email: 'email' } Commented Mar 4, 2015 at 19:55

4 Answers 4

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';
Sign up to request clarification or add additional context in comments.

Comments

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';

1 Comment

I assumed OP wanted to keep his array setup, but this is probably what he really wants.
0

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

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

Comments

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.

Comments

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.