-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]
0

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

5 Comments

so 0:Object it means 0 is properties ?
@Mahi Yes, you are right.
@PraveenKumar so we can make array using {}?
@Mahi yes, but if you are using {} you cannot use invalid variable names, where, integers are invalid. :)
@Mahi no, but you can convert an indexed object to an array with Array.prototype.slice.call(obj) If you need to iterate over something you should use an array. If you need property accessors you should use an object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.