简体   繁体   中英

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]

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 );
}

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]

您可以使用数组索引获取对象

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

在您的情况下,您应该尝试:

item.condition[0].conditionDisplayName
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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM