-1

In the console I have an array that looks like this:

Array[3]
  0: Object
  1: Object
  2: Object
  columns: Array[2]
  length: 3
  __proto__: Array[0]

The last item hasn't an index, but the name columns.

How can I reproduce something similar? I tried:

var columns = ["age", "population"];
var myObj = [
  {age: "<5",     population: 2704659},
  {age: "5-13",  population: 4499890},
  {age: "14-17", population: 2159981},
  columns
];
console.log(myObj);

But it gives me this:

// Console
Array[4]
  0: Object
  1: Object
  2: Object
  3: Array[2]
  length: 4
  __proto__: Array[0]
isar
  • 1,661
  • 1
  • 20
  • 39

1 Answers1

1

An array is actually just an object that you can attach properties to like any other.

You should avoid adding properties like this though.

var columns = ["age", "population"];
var myObj = [
  {age: "<5",     population: 2704659},
  {age: "5-13",  population: 4499890},
  {age: "14-17", population: 2159981}
];

myObj.columns = columns

console.dir(myObj); // check the browsers actual console to see the output

// this proves that Array inherit's from Object
console.log(myObj instanceof Array)
console.log(myObj instanceof Object)

I think you are better off creating your own object of a Table that has the different properties with accessors for when you need them.

// define the Table class
class Table {
  constructor(columns, rows) {
    this.columns = columns
    this.rows = rows
  }
  getColumns() {
    return this.columns
  }
  getRows(index) {
    return typeof index !== 'undefined'
      ? this.rows[index]
      : this.rows
  }
  getTable() {
    return [
      this.columns,
      ...this.rows.map(row => Object.values(row))
    ]
  }
}

var columns = ["age", "population"];
var myObj = [
  {age: "<5",     population: 2704659},
  {age: "5-13",  population: 4499890},
  {age: "14-17", population: 2159981}
]

const table = new Table(columns, myObj)

console.log(table)
console.log(table.getColumns())
console.log(table.getRows())
console.log(table.getTable())
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
synthet1c
  • 6,152
  • 2
  • 24
  • 39