Displaying array properties in Safari's console

Viewed 486

Given the following snippet:

const myArray = ["foo", "bar", "baz"];
myArray.someProperty = "foobar";
console.log(myArray)

In Safari, it will display only this:

["foo", "bar", "baz"] (3)

In other browsers, like Chrome and Firefox, it will display the someProperty property, along with native properties like length:

Array(3)
  0: "foo"
  1: "bar"
  2: "baz"
  someProperty: "foobar"
  length: 3

It's worth mentioning that things like console.dir, console.table or console.log(JSON.stringify(myArray)) won't work for displaying such properties.

Is there any workaround for this limitation in Safari? Obviously I could just do console.log(myArray.someProperty), but my main goal is checking what properties the array have (I'm not the one creating the array, it's being created by a JS library), so those properties are unknown to me.

2 Answers

You need to convert it to Object first

console.log(Object.assign({}, myArray))

It will show all of your array properties

Based on the accepted answer I can even strip the numeric keys (which are the common array content) and log only the array's properties, if any:

const myArray = ["foo", "bar", "baz"];
myArray.someProperty = "foobar";
myArray.someOtherProperty = "barbaz";

logArrayProperties(myArray)

function logArrayProperties(arr) {
  Object.entries(Object.assign({}, arr)).forEach(row => {
    if (isNaN(row[0])) console.log(row[0] + ": " + row[1])
  });
};

Related