简体   繁体   中英

Get an item of array in javascript

I have a function, who works fine, but when success i get data, and this data is an array.

success: function(data) {
console.log(data);
}

this data return :

{"idResultat":172825,"idClientCat":1,"idClientLegende":"Tiers L\u00e9gitime","couleurCat":"#0062bd","couleurText":"#FFF"}

But when i try to get for example 'couleurCat', i have undefined. I have try like this :

data['couleurCat']
data.couleurCat

but always undefined

You need to restructure your string as JSON before you can access elements. To access the JSON object in JavaScript, parse it with JSON.parse() , and access it via . or [] .

In your case, try using:

 JSON.parse(data).couleurCat;

.Try to parse the string JSON.parse(data) and try to access it.

code

 data= JSON.parse(data)
 data['couleurCat']

You said " but when success i get data, and this data is an array. " So you should be trying

data[0].couleurCat

You will have to specify the index of array then access the property.

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