Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying array properties in Safari's console

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.

like image 850
Megaptera novaeangliae Avatar asked Oct 25 '19 09:10

Megaptera novaeangliae


People also ask

How do you console an array in JavaScript?

Just pass the Array object into a console. log() to print the array as comma-separated in JavaScript. And if you want to print array elements wise then use loop (while or for-loop).

What console method will you call to see array data in a table?

The console. table() method displays tabular data as a table. This function takes one mandatory argument data , which must be an array or an object, and one additional optional parameter columns .

What does find() return?

The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found.


2 Answers

You need to convert it to Object first

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

It will show all of your array properties

like image 60
Vo Kim Nguyen Avatar answered Oct 18 '22 07:10

Vo Kim Nguyen


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])
  });
};
like image 20
Megaptera novaeangliae Avatar answered Oct 18 '22 05:10

Megaptera novaeangliae