461

Below, you can see the output from these two logs. The first clearly shows the full object with the property I'm trying to access, but on the very next line of code, I can't access it with config.col_id_3 (see the "undefined" in the screenshot?). Can anyone explain this? I can get access to every other property except field_id_4 as well.

console.log(config);
console.log(config.col_id_3);

This is what these lines print in Console

Console output

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Brian Litzinger
  • 5,409
  • 3
  • 23
  • 21
  • 8
    can you try `console.log(JSON.stringify(config));` ans share the o/p – Arun P Johny Jul 09 '13 at 11:25
  • and what about upload_paths? can you get upload_paths in console.log(config.upload_paths); – zzlalani Jul 09 '13 at 11:26
  • 2
    also try this, if this works console.log(config['col_id_3']); – zzlalani Jul 09 '13 at 11:27
  • 8
    this worked for me. using stringified output as new input for a working object: JSON.parse(JSON.stringify(obj)) – Tope Jan 27 '16 at 13:04
  • 4
    Stringifying and then parsing did not solve the issue for me, for some reason. However parsing outright did. `JSON.parse(obj)` – JacobPariseau Jan 02 '17 at 08:20
  • I know this is an old post ... `what tool did you use for annotation?` I've been wondering about that for a few months, but none of the tools I've found (Gimp, Nimbus screenshot, MS Paint, IrfanView) for Windows make this ubiquitous white background with drop shadow. Is this a native MAC OS feature? – Eric Hepperle - CodeSlayer2010 Dec 06 '18 at 19:30
  • For me the problem was that I was executing the javascript that used the object before the javascript that defined the object in the window. – Ryan Walker Apr 03 '19 at 23:01
  • 9
    For some reason all the answers explain how to log the object without the key, not how to access the key – remidej Sep 02 '19 at 09:50
  • 1
    @EricHepperle-CodeSlayer2010, looks like its Skitch. – opensource-developer Jan 29 '20 at 09:40
  • Strange how all of us can be engrossed on __console.log()__ instead of __why data access fails yet the key and data is present__ – Ajowi Feb 11 '22 at 15:08
  • `JSON.parse(JSON.stringify(config)).col_id_3` works. but it's ugly... I'm sure there's a reason why it works this way, but I was unable to find one. – Paul Jurczyk Sep 10 '22 at 00:30
  • If you find the output of `console.log(yourObject)` is {} with a little blue icon [i], check [this](https://stackoverflow.com/questions/17546953/cant-access-object-property-even-though-it-shows-up-in-a-console-log/39606500#39606500). – tinystone May 11 '23 at 06:48

36 Answers36

402

The output of console.log(anObject) is misleading; the state of the object displayed is only resolved when you expand the Object tree displayed in the console, by clicking on >. It is not the state of the object when you console.log'd the object.

Instead, try console.log(Object.keys(config)), or even console.log(JSON.stringify(config)) and you will see the keys, or the state of the object at the time you called console.log.

You will (usually) find the keys are being added after your console.log call.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Matt
  • 74,352
  • 26
  • 153
  • 180
  • 21
    Is this behaviour a bug or a feature? If it's a feature, what is the reasoning behind it? – ESR May 31 '18 at 04:56
  • 10
    How does one get around this then? Setting a timeout does NOT seem like a good solution. – Sahand Jul 13 '18 at 09:38
  • 23
    Then how we can access this property, from the object? – Rohit Sharma Sep 01 '18 at 07:20
  • To clarify, is the behaviour of the `>` button different depending on whether an array is being expanded, or an object? – Flimm Oct 04 '18 at 14:41
  • Doing some testing, it seems that you have come across this issue even with an array, so I would recommend doing JSON.stringify instead. – Flimm Oct 04 '18 at 14:47
  • 1
    This may be caused by setting the property asynchronusly. – PowerAktar Oct 10 '20 at 15:41
  • 5
    From MDN: "Don't use `console.log(obj)`, use `console.log(JSON.parse(JSON.stringify(obj)))`. This way you are sure you are seeing the value of `obj` at the moment you log it. Otherwise, many browsers provide a live view that constantly updates as values change. This may not be what you want." https://developer.mozilla.org/en-US/docs/Web/API/Console/log – Raffi Dec 14 '22 at 17:31
  • 1
    This worked for me @Raffi, thanks! But kind of wtf – Ezeeroc Aug 01 '23 at 17:53
103

I've just had this issue with a document loaded from MongoDB using Mongoose.

When running console.log() on the whole object, all the document fields (as stored in the db) would show up. However some individual property accessors would return undefined, when others (including _id) worked fine.

Turned out that property accessors only works for those fields specified in my mongoose.Schema(...) definition, whereas console.log() and JSON.stringify() returns all fields stored in the db.

Solution (if you're using Mongoose): make sure all your db fields are defined in mongoose.Schema(...).

ramin
  • 1,182
  • 1
  • 7
  • 5
  • 2
    Great explanation of this problem, I figured Mongoose would let me query the json without a schema (in an external script), but would prevent writes. It appears to work because the _id is present, and the console.log says everything else should be accessible, but isn't. Bizarre. – bstar Sep 02 '16 at 18:10
  • 10
    Turns out I was seeing this because `JSON.stringify()` (and Node's `console.log()`) change their behaviour if the object given has a `.toJSON()` function. The output you see is what `.toJSON()` returns, and not the original object. Mongoose gives you model objects with a `.toJSON()` that gives the underlying db object. The model object only has accessors for fields you define in the schema, but then all the db fields appear when you log it because you're actually seeing the underlying object returned by `.toJSON()`. – ramin Sep 09 '16 at 20:50
  • Why doesn't mongoose allow to read other properties do you have any idea? – Kannan T May 22 '18 at 07:23
  • This was helpful for me when uploading a CSV into mongodb and fetching the property. Make sure your names match. Great answer thank you. – 9BallOnTheSnap Feb 25 '19 at 19:54
  • 6
    Thank you for this. I was going mad seeing it in the console and not being able to access it. Added the value to my schema and I am good to go. Thanks again! – MaxPower Jul 11 '19 at 05:48
  • 2
    In case you'd like to access properties that are not defined in the schema, you can also use the `toObject()` method to convert the returned document to a JavaScript object. See https://mongoosejs.com/docs/guide.html#toObject – adamgy Sep 21 '21 at 00:45
  • It is very helpful. I ran into the same problem today while using mongoose+express. – mukund Oct 01 '21 at 13:59
  • This is the real answer here – Murat Colyaran Oct 20 '21 at 13:08
34

Check if inside the object there's an array of objects. I had a similar issue with a JSON:

    "terms": {
        "category": [
            {
                "ID": 4,
                "name": "Cirugia",
                "slug": "cirugia",
                "description": "",
                "taxonomy": "category",
                "parent": null,
                "count": 68,
                "link": "http://distritocuatro.mx/enarm/category/cirugia/"
            }
        ]
    }

I tried to access the 'name' key from 'category' and I got the undefined error, because I was using:

var_name = obj_array.terms.category.name

Then I realised it has got square brackets, that means that it has an array of objects inside the category key, because it can have more than one category object. So, in order to get the 'name' key I used this:

var_name = obj_array.terms.category[0].name

And That does the trick.

Maybe it's too late for this answer, but I hope someone with the same problem will find this as I did before finding the Solution :)

Asaf Lopez
  • 539
  • 5
  • 8
34

I had the same issue. Solution for me was using the stringified output as input to parsing the JSON. this worked for me. hope its useful to you

var x =JSON.parse(JSON.stringify(obj));
console.log(x.property_actually_now_defined);
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Tope
  • 938
  • 2
  • 11
  • 15
  • 2
    Yes it worked, but why is this required? I already have a JSON, why I need to do this? – jain Nov 29 '16 at 08:37
  • @dilpeshjain I'm not exactly sure, but I would venture that we dont actually have JSON already (perhaps there is a lazy loading type scenario going on, i am not knowledgeable enough about that at the moment) , but passing whatever we do have into JSON.stringify requires a string to be returned (like the console.log call needs for printing). Because I know I can at least get a string, then I can use that string to create a JSON object for sure right away. – Tope Sep 02 '17 at 19:28
  • 22
    @jain you need this because javascript is a horrible language –  Sep 02 '19 at 02:46
33

The property you're trying to access might not exist yet. Console.log works because it executes after a small delay, but that isn't the case for the rest of your code. Try this:

var a = config.col_id_3;    //undefined

setTimeout(function()
{
    var a = config.col_id_3;    //voila!

}, 100);
Lai Xue
  • 1,523
  • 1
  • 15
  • 17
  • 4
    I used to onload method to get my object values.But still gives me undefined at the first time.. This language makes me dead day by day – Teoman Tıngır Nov 23 '18 at 15:28
  • an easy solution would be to implement a watcher promise that checks if the desired property is defined with setTimeout, and resolves + clears the timeout once the property becomes available. – Lai Xue Nov 26 '18 at 04:49
  • 1
    Wow. In my some 15 years of web programming I had never encountered this and never put thought into how console log works. Your answer helped clear some of that up. – Kai Qing Mar 09 '20 at 18:15
16

In my case I was passing an object to a promise, within the promise I was adding more key/values to the object and when it was done the promise returned the object.

However, a slight over look on my part, the promise was returning the object before it was fully finished...thus the rest of my code was trying to process the updated object and the data wasn't yet there. But like above, in the console, I saw the object fully updated but wasn't able to access the keys - they were coming back undefined. Until I saw this:

console.log(obj) ;
console.log(obj.newKey1) ;

// returned in console
> Object { origKey1: "blah", origKey2: "blah blah"} [i]
    origKey1: "blah"
    origKey2: "blah blah"
    newKey1: "this info"
    newKey2: "that info"
    newKey3: " more info"
> *undefined*

The [i] is a little icon, when I hovered over it it said Object value at left was snapshotted when logged, value below was evaluated just now. Thats when it occurred to me that my object was being evaluated before the promise had fully updated it.

rolinger
  • 2,787
  • 1
  • 31
  • 53
14

I just encountered this issue with objects generated by csv-parser from a CSV file that was generated by MS Excel. I was able to access all properties except the first property - but it would show up ok if I wrote the whole object using console.log.

Turned out that the UTF-8 CSV format inserts 3 bytes (ef bb bf) at the start corresponding to an invisible character - which were being included as part of the first property header by csv-parser. Solution was to re-generate the CSV using the non-UTF option and this eliminated the invisible character.

Mike Rizzo
  • 141
  • 1
  • 3
12

I struggled with this issue today, and thought I'll leave a reply with my solution.

I was fetching a data object via ajax, something like this: {"constants": {"value1":"x","value2":"y"},"i18n" {"data1":"x", "data2":"y"}}

Let's say this object is in a variable called data. Whenever I referenced data.i18n I got undefined.

  1. console.log(data) showed the object as expected
  2. console.log(Object.keys(data)) said ["constants","i18n"] as expected
  3. Renaming i18n to inter didn't change anything
  4. I even tried to switch the data to make "i18n" the first object
  5. Moved code around to make absolutely sure the object was completely set and there was no problem with the ajax promise.

Nothing helped... Then on the server side I wrote the data to the php log, and it revealed this:

{"constants": {"value1":"x","value2":"y"},"\u045618n" {"data1":"x", "data2":"y"}}

The "i" in the index key was actually a u0456 (cyrillic i). This was not visible in my php editor or the browser console log. Only the php log revealed this... That was a tricky one...

koralgoll
  • 45
  • 6
Jette
  • 2,459
  • 28
  • 37
  • 1
    This was also my issue; had a Cyrillic 'c' character instead in some of the instances. I found it by searching my file for the string I expected; the suspicious one was not selected, so that told me there was a wrong character that was invisible to the eye. – knighter Oct 16 '18 at 21:37
  • This answer actually helped me find my solution. My issue was I had misspelled my variable name. I did "udpate" instead of "update" lol – Savlon Apr 19 '20 at 04:43
12

My data was just json data string . (This variable was stored as json string in the session).

console.log(json_string_object)

-> returns just the representation of this string and there is no way to make difference whether is string or object.

So to make it work I just needed to convert it back to real object:

object = JSON.parse(json_string_object);
makkasi
  • 6,328
  • 4
  • 45
  • 60
  • 1
    This was the only answer that worked for me and is also mentioned in the comments of the original question, this should be higher. – abagh0703 Mar 22 '18 at 02:11
11

In 2018 Mozilla warns us in the Mozilla Docs here!

I quote "Logging Objects":

Don't use console.log(obj);, use console.log(JSON.parse(JSON.stringify(obj)));.

This way you are sure you are seeing the value of obj at the moment you log it.

Mateut Alin
  • 1,173
  • 4
  • 17
  • 34
9

If this is an issue occurring when working with Mongoose, the following may happen:

console.log(object)

returns everything, including the desired key.

console.log(object.key)

returns undefined.

If that is happening, it means that the key is missing from the Mongoose Schema. Adding it in will resolve the issue.

Julian E.
  • 4,687
  • 6
  • 32
  • 49
8

For me it turned out to be a Mongoose-related problem.

I was looping over objects that I got from a Mongo query. I just had to remove:

items = await Model.find()

And replace it by:

items = await Model.find().lean()
remidej
  • 1,428
  • 1
  • 14
  • 21
4

This might help somebody as I had a similar issue in which the JSON.parse() was returning an object that I could print on the console.log() but I couldn't acccess the specific fields and none of the above solution worked for me. Like using the combination of JSON.parse() with JSON.stringify().

var jsonObj = JSON.parse(JSON.stringify(responseText))

// where responseText is a JSON String returned by the server.

console.log(jsonObj) ///Was printing the object correctly
console.log(jsonObj.Body) /// Was printing Undefined  

I ended up solving the problem by using a different parser provided by ExtJs Ext.decode();

var jsonObj = Ext.decode(responseText)
console.log(jsonObj.Body) //Worked...
user_CC
  • 4,686
  • 3
  • 20
  • 15
3

I had the same issue and no solution above worked for me and it sort of felt like guess work thereafter. However, wrapping my code which creates the object in a setTimeout function did the trick for me.

setTimeout(function() {
   var myObj = xyz; //some code for creation of complex object like above
   console.log(myObj); // this works
   console.log(myObj.propertyName); // this works too
});
Tushar Shukla
  • 5,666
  • 2
  • 27
  • 41
3

I've just had the same issue with a document loaded from MongoDB using Mongoose.

Turned out that i'm using the property find() to return just one object, so i changed find() to findOne() and everything worked for me.

Solution (if you're using Mongoose): Make sure to return one object only, so you can parse its object.id or it will be treated as an array so you need to acces it like that object[0].id.

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
  • This helped me some by helping me clean up my code. I have a function doing the Mongoose query (with `.findOne()` now, thanks to you) and it returns an Object I can access in dot notation inside the function. I call that Mongoose function further down in code by `const test = await mongoFunction(query)` and, unfortunately, my problem is the returned `test` is an array with the Object inside of it `[ {object} ]` that I cannot access in dot notation. It is driving me nuts! – Jeremy M Jul 19 '20 at 12:22
  • This was my solution! Now *console.log()* works normal! Thanks – Ramiro Arizpe Giacomelli Jun 09 '21 at 17:25
2

if you're using TYPESCRIPT and/or ANGULAR, it could be this!

.then((res: any) => res.json())

setting the response type to any fixed this issue for me, I couldn't access properties on the response until i set res: any

see this question Property '_body' does not exist on type 'Response'

Philipp
  • 2,787
  • 2
  • 25
  • 27
russiansummer
  • 1,361
  • 15
  • 16
2

In My case, it just happens to be that even though i receive the data in the format of a model like myMethod(data:MyModelClass) object till the received object was of type string. Which is y in console.log(data) i get the content. Solution is just to parse the JSON(in my case)

const model:MyMOdelClass=JSON.parse(data);

Thought may be usefull.

2

I've had similar issue, hope the following solution helps someone.
You can use setTimeout function as some guys here suggesting, but you never know how exactly long does your browser need to get your object defined.

Out of that I'd suggest using setInterval function instead. It will wait until your object config.col_id_3 gets defined and then fire your next code part that requires your specific object properties.

window.addEventListener('load', function(){

    var fileInterval = setInterval(function() {
        if (typeof config.col_id_3 !== 'undefined') {

            // do your stuff here

            clearInterval(fileInterval); // clear interval
        }
    }, 100); // check every 100ms

});
Oleksa O.
  • 827
  • 8
  • 16
1

I had a similar issue or maybe just related.

For my case I was accessing properties of an object but one was undefined. I found the problem was a white-space in the server side code while creating the key,val of the object.

My approach was as follows...

creating my object... notice the white-space in "word"

response I get from my REST API

javascript code to log the values

log results from console

After removing the white-space from the server-side code creating the object, I could now access the property as below...

result after removing whitespace

This might not be the issue with the case of the subject question but was for my case and may be so for some one else. Hope it helps.

rey_coder
  • 422
  • 8
  • 12
1

I just encountered this issue as well, and long story short my API was returning a string type and not JSON. So it looked exactly the same when you printed it to the log however whenever I tried to access the properties it gave me an undefined error.

API Code:

     var response = JsonConvert.DeserializeObject<StatusResult>(string Of object);
     return Json(response);

previously I was just returning:

return Json(string Of object);
Zapnologica
  • 22,170
  • 44
  • 158
  • 253
1

First thing check the type like below:

console.log(typeof config);

If the command above prints object then it is very easy you just use the bracket notation. Bracket notation can be quite useful if you want to search for a property’s values dynamically.

Execute the command below:

console.log(config[col_id_3]);

If it a string you need to parse in object first. To do that you need to execute the command below:

var object = JSON.parse(config);

And after that use bracket notation to access the property like below:

console.log(object[col_id_3]);
Rando Shtishi
  • 1,222
  • 1
  • 21
  • 31
0

I had an issue like this, and found the solution was to do with Underscore.js. My initial logging made no sense:

console.log(JSON.stringify(obj, null, 2));

> {
>   "code": "foo"
> }

console.log(obj.code);

> undefined

I found the solution by also looking at the keys of the object:

console.log(JSON.stringify(Object.keys(obj)));

> ["_wrapped","_chain"]

This lead me to realise that obj was actually an Underscore.js wrapper around an object, and the initial debugging was lying to me.

Marcus Downing
  • 10,054
  • 10
  • 63
  • 85
0

I had similar problem (when developing for SugarCRM), where I start with:

var leadBean = app.data.createBean('Leads', {id: this.model.attributes.parent_id});

// This should load object with attributes 
leadBean.fetch();

// Here were my attributes filled in with proper values including name
console.log(leadBean);

// Printed "undefined"
console.log(leadBean.attributes.name);

Problem was in fetch(), its async call so I had to rewrite my code into:

var leadBean = app.data.createBean('Leads', {id: this.model.attributes.parent_id});

// This should load object with attributes 
leadBean.fetch({
    success: function (lead) {
        // Printed my value correctly
        console.log(lead.attributes.name);
    }
});
Mariyo
  • 486
  • 7
  • 15
0

Just in case this is helpful for someone, I had a similar problem, and it's because someone created an override for .toJSON in the object I was working with. So the object was something like:

{
  foo: {
         bar: "Hello"
         baz: "World"
       }
}

But .toJSON() was:

toJSON() {
  return this.foo
}

So when I called JSON.stringify(myObject) it returned "{"bar": "Hello", "baz": "World"}". However, Object.keys(myObject) revealed the "foo".

emote_control
  • 745
  • 6
  • 21
  • `toJson()` this is the point that nobody has mentioned here. I don't know why this answer was downvoted since this is a way to create an object that has a different value from it's json or console representation. I didn't know it existed until I uncovered it in a different answer, and I think this answer should be upvoted since it is a point to consider with these types of issues. – Rick Love Feb 26 '20 at 14:59
  • Considering the number of answers that have exactly 0 points, I think someone just went through downvoting everything. – emote_control Feb 27 '20 at 15:35
0

I faced the same problem today. In my case the keys were nested, i.e key1.key2. I split the keys using split() and then used the square bracket notation, which did work for me.

var data = {
    key1: {
          key2: "some value"
       }
}

I split the keys and used it like this, data[key1][key2] which did the job for me.

gunnerwhocodes
  • 484
  • 5
  • 13
0

I had the same issue today. Problem was caused by uglify-js. After I executed same non-uglified code problem was solved. Removing of

--mangle-props

from uglify-js was enough to have working uglified code.

Perhaps, the best practice is to use some prefix for properties that has to be mangled with regex rule for uglify-js.

Here is the source:

var data = JSON.parse( content);
...
this.pageIndex = parseInt(data.index);
this.pageTotal = parseInt(data.total);
this.pageLimit = parseInt(data.limit); 

and here is how it was uglified:

var n = JSON.parse( t);
...
this._ = parseInt(n.index), this.g = parseInt(n.total), this.D = parseInt(n.C)
0

None of the JSON stringify/parse worked for me.

formValues.myKey:               undefined
formValues.myKey with timeout:  content

I wanted the value of formValues.myKey and what did the trick was a setTimeout 0 like in the example below. Hope it helps.

console.log('formValues.myKey: ',formValues.myKey);
setTimeout( () => { 
  console.log('formValues.myKey with timeout: ', formValues.myKey);
}, 0 );
B--rian
  • 5,578
  • 10
  • 38
  • 89
anacampesan
  • 105
  • 10
0

I had a similar issue today in React. Eventually realised that the problem was being caused by the state not being set yet. I was calling user.user.name and although it was showing up in the console, I couldn't seem to access it in my component till I included a check to check if user.user was set and then calling user.user.name.

Adebola
  • 549
  • 1
  • 7
  • 11
0

Check whether you had applied any filters in the console. It happens to me in chrome console.

Mahee Gamage
  • 413
  • 4
  • 12
0

I also had this frustrating problem, I tried the setTimeout() and the JSON.stringify and JSON.parse solutions even if I knew it wouldn't work as I think they're mostly JSON or Promise related problems, sure enough it didn't work. In my case though, I didn't notice immediately that it was a silly mistake. I was actually accessing a property name with a different casing. It's something like this:

const wrongPropName = "SomeProperty"; // upper case "S"
const correctPropName = "someProperty"; // lower case "s"
const object = { someProperty: "hello world!" };

console.log('Accessing "SomeProperty":', object[wrongPropName]);
console.log('Accessing "someProperty":', object[correctPropName])

It took me a while to notice as the property names in my case can have either all lower case or some having mixed case. It turned out that a function in my web application has something that makes a mess of my property names (it has a .toLowerCase() next to the generated key names ).

So, lesson learned, check property name casing more properly.

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
jp06
  • 185
  • 3
  • 8
0

I was not getting the MongoDB error message in the thrown error in my NodeJS API response, so I did the following

// It was not working
console.log(error.message) // prints the error
let response = error;
// message property was not available in the response.
/* 
{
  "status": "error",
  "error": {
    "driver": true,
    "name": "MongoError",
    "index": 0,
    "code": 11000,
    "keyPattern": {
      "event_name": 1
    },
    "keyValue": {
      "event_name": "followup"
    }
  }
}
*/
// so I did this
let message = error.message;
let response = JSON.parse(JSON.stringify(error));
response.message = message;
// message property is now available in the response.
/* 
{
  "status": "error",
  "error": {
    "driver": true,
    "name": "MongoError",
    "index": 0,
    "code": 11000,
    "keyPattern": {
      "event_name": 1
    },
    "keyValue": {
      "event_name": "followup"
    },
    "message": "E11000 duplicate key error collection: mycollections.notificationevents index: event_name_1 dup key: { event_name: \"followup\" }"
  }
}
*/
Suhail Akhtar
  • 1,718
  • 15
  • 29
0

In the context of this answer: https://stackoverflow.com/a/52994419

The solution to re-generate the files may not always be feasible. To strip out the "non-space" characters before the string. So, if you can trim the field names, that would clean up things.

Something like this:

const records = parse(csvData, {
      columns: (colNameArray) => {
        return colNameArray.map((value, index) => {          
          return index === 0 ? value.trim() : value;
        });
      },
      onRecord: mapper.mapRow
    });

If you don't care about the performance on this one, can skip the index check too.

0

I have tried plenty of answers on this question finally found what has happen.

Although object is print on console.log(foo) get and set methods generated only when using new Foo() you have to initialize instance with plane js object

please have a look : https://stackoverflow.com/a/41153231/5954248

Nilupul Heshan
  • 580
  • 1
  • 5
  • 18
0

This is what worked for me (using Vue JS):

const auth = undefined;

console.log(auth); // undefined

// ✅ No error
console.log(auth?.user?.name); // undefined
Karam Qusai
  • 713
  • 12
  • 16
-1

Well I passed by a situation that really scared me about new loops and thanked the old school I am.

The forEach loop and also for( a in obj ) loop BOTH produces FALSE INFORMATION and bugs, depending on the type of object and its properties!!

The old and good

for(var i=0, max=arr.length; i<max; i++)
{ //Properties available correctly!

   arr[i].property        //both work inside old school loop!
   arr[i][property]  
}             
Sergio Abreu
  • 2,686
  • 25
  • 20
-1

I faced the same problem.

From the server, I was returning data in json_encode. Like this

 echo json_encode($res);  

After I returned a simple PHP array without json_encode, it solved the problem.

return $res;
Nomi
  • 27
  • 1
  • 6
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 28 '22 at 13:14