0

I'm having a mental block. How may I access the data inside this javascript object that's returned from an ajax function?

I was thinking something like this would work:

data[0].id would return 1 
data[1].category.description would return "MEN"

Help would be appreciated!

"[ {
  "id" : 1,
  "description" : "PANTS",
  "price" : 10.99,
  "category" : {
    "id" : 1,
    "description" : "MEN"
  },
  "customerType" : {
    "id" : 1,
    "type" : "COUNTER"
  }
}, {
  "id" : 2,
  "description" : "SHIRT",
  "price" : 4.99,
  "category" : {
    "id" : 1,
    "description" : "MEN"
  },
  "customerType" : {
    "id" : 1,
    "type" : "COUNTER"
  }
} ]"
2
  • It looks like you're pasting the raw string, which I would assume you haven't parsed into an object. Commented Jun 6, 2017 at 1:07
  • Please delete this question. Commented Jun 6, 2017 at 1:14

2 Answers 2

1

That should work, just loop over it

dataLength=data.length;
for(var i=0;i<dataLength;i++){
    var dataID = data[i].id;
    var dataCatagory = data[i].category.description;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for fast response, I was just posting my own response as you typed yours. Duh.. Just a dumb brain freeze
I'll accept your post in 7 minutes LOL Thanks again
Don't worry, it happens to all of us :P
per comment above by zzzzBov I wasn't parsing it first, then I could traverse it as normal. Thought Id add that to the comment in case someone else had a brainfreeze like me. Just do JSON.parse(data) then use a loop or whatever and it'll work as any other normal javascript object
0

ah jeez.. I figured out a simple way to get the data out. I can do something like this:

currentrow = data[i];
id = currentrow.id;

Or use id or the other values as such. Nevermind my posting, I'm an idiot sometimes

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.