smartfuse
smartfuse

Reputation: 51

How to access element in JSON and Javascript

How do I access something like this with Javascript and Jquery?

"condition" : [{"conditionId":["3000"],"conditionDisplayName":["Used"]}]

(this is just an excerpt)

I tried using item.condition and I got:
[{"conditionId":["3000"],"conditionDisplayName":["Used"]}] as a result.

How do I get the conditionDisplayName?

I've also tried using : item.condition.conditionDisplayName but it doesn't work nor does item.condition[1]

Upvotes: 0

Views: 75

Answers (5)

colestrode
colestrode

Reputation: 10658

condition is an array, as is conditionDisplayName, so you will need to access their members using an index. For example, to get the first displayName of the first condition you would do:

var displayName = item.condition[0].conditionDisplayName[0]

Upvotes: 2

Chris Dixon
Chris Dixon

Reputation: 9167

var array = [{"conditionId":["3000"],"conditionDisplayName":["Used"]}]

// Not right - show ["Used"]
console.log(array[0].conditionDisplayName);

// Right - show "Used"
console.log(array[0].conditionDisplayName[0]);

You can see this here: http://jsfiddle.net/bs9kx/

Upvotes: 1

WooCaSh
WooCaSh

Reputation: 5212

In your case you should try:

item.condition[0].conditionDisplayName

Upvotes: 1

MrCode
MrCode

Reputation: 64526

You're almost there but your condition is an array with one object so you need to use the array notation to access it:

var displayName = item.condition[0].conditionDisplayName;

If there could be more than one object in the array, you can use a loop:

for(var i=0; i<item.condition.length; i++) {
    console.log( item.condition[i].conditionDisplayName );
}

Upvotes: 2

Adil
Adil

Reputation: 148110

You can use array index to get the object

var displayName = obj.condition[0].conditionDisplayName;

Upvotes: 1

Related Questions