Home > front end >  JSON.stringify(list) shows an array of strings, however, Array.isArray(list) is false
JSON.stringify(list) shows an array of strings, however, Array.isArray(list) is false

Time:12-21

I am currently trying to debug the issue in the title.

Here's some additional information:

  • I am receiving the list from a DynamoDB set.
  • JSON.stringify(list) prints: ["elt1","elt2"]
  • Array.isArray(list) === false
  • list.map is undefined, list.forEach is undefined
const list2 = JSON.parse(JSON.stringify(list))
Array.isArray(list2) === true

I have tried the above hack, and it does solve the issue- but it is definitely not conventional.

CodePudding user response:

You've made an erroneous assumption: just because something produces an Array when run through JSON.stringify() does not necessarily mean it in itself is an Array to start. Consider this example:

class MyClass {
  toJSON() {
    return ['a', 'b'];
  }
}

const list = new MyClass();

console.log(JSON.stringify(list));
console.log(Array.isArray(list));
console.log(list.map);
console.log(list.forEach);

In other words - it's entirely possible for a class to override the toJSON() method and fundamentally alter how it is processed by JSON.stringify(). I would suspect what you're encountering is that list is not really an Array (as you allude) but rather some other type that behaves this way when being stringified.

CodePudding user response:

It's return valid output (list.map is undefined, list.forEach is undefined),t because JSON.stringify() convert into a string and you can't apply any array function on in it.

  • Related