0

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

6
  • 1
    what does typeof return for data? Commented May 18, 2017 at 10:09
  • 1
    jsbin.com/tiyedozedi/1/edit?js,console — It works fine when I test it. Try providing a real minimal reproducible example instead of fragments of disconnected code. Commented May 18, 2017 at 10:09
  • 1
    Looks like data is a string, convert it to an object before retrieving. Commented May 18, 2017 at 10:09
  • 1
    Could you post a larger example of what you are doing? I suspect you are accessing data before it is available. Commented May 18, 2017 at 10:10
  • Console.log doesn't always log the object as it is at the moment of the log. try logging Object.keys(data) to see which keys are defined at that moment Commented May 18, 2017 at 10:11

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

I suspect that this is the right answer, but it needs expanding. I don't know why it's been downvoted.
@SpoonMeiser Added some explenations.
@SpoonMeiser Don't know why the downvote too... Thanks anyway.
1

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

code

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

Comments

0

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.

1 Comment

I think he is not getting an array.

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.