0

I can't seem to figure out how to get the following results...

var errors;
errors = { username: "username_error", email: "email_error" };

...when looping through data in this code:

var errors = {}
$.each(data,function(k,v)
{
   errors[k] = v; // doesn't seem to work
});

It does produce an object yet in a different format.

EDIT: console log.

Expected results:

Object
email: "email_error"
username: "username_error"
__proto__: Object
 edit:25
Object
__proto__: Object

Generated results:

Object
email: Array[1]
0: "email_error"
length: 1
__proto__: Array[0]
username: Array[1]
0: "username_error"
length: 1
__proto__: Array[0]
__proto__: Object
4
  • @FrankieTheKneeMan: data is a JSON object. k and v are strings. Commented Sep 1, 2012 at 0:48
  • ... Right. Can you do a console.log(data) and put that here? Commented Sep 1, 2012 at 0:51
  • Are you sure the objects in data aren't arrays? Commented Sep 1, 2012 at 0:58
  • 1
    STILL don't know what the hell is in data! PLEASE do a console.log(data). It will help us eliminate the easy fixes. Commented Sep 1, 2012 at 0:59

2 Answers 2

2

By the results you posted with the log output, it seems the objects in data are arrays. Try replacing the assignment with this:

errors[k] = v.length>0 ? v[0] : ""
Sign up to request clarification or add additional context in comments.

3 Comments

indeed it was an array. v[0] worked. I hate mjself for literally wasting hours on this :) thank you.
all you had to do was a console.log(data), the console is your friend, use it...
the funny thing is... I was using it but I was just too blind to notice the array type.
1

Try this

var errors = {}
$.each(data,function(k,v)
{
   errors[k] = v[0];

});

DEMO.

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.