1

I have a csv file with 5000 rows, with thirty fields per row (The data represent measurements of the concentration of different chemical elements).

I want to parse and visualize the data with D3js. After reading in the file I have an array with length 5000. Here, each element is an object with the measurements of the various chemical elements. measurements[5].Aluminium for instance returns the concentration of Aluminium at the fifth measurement.

Now I rather want to have arrays for each element with all their very measurments as elements. While this is easy with a for-loop, I want to try the map function.

Aluminium = measurements.map(function(row){
    return row.Aluminium;
});

This works and I could do this for each element but I would prefer to have the element as a parameter itself.

function selectElement(elementname){
      measurements.map(function(row){
          return row.elementname;
      });
};

Aluminium = selectElement('Aluminium');
Iron = selectElement('Iron');

And this is where I am stuck.

verticoe
  • 103
  • 7
  • What is your question? Don't you already have the element as a parameter? – Eli Sadoff Nov 11 '16 at 20:03
  • In JavaScript you can access object properties with square-brackets notations such as `row[elementname]` would be equivalent of `row.Aluminium` for `elementname === 'Aluminium'`. – Kuba Wyrostek Nov 11 '16 at 20:04

2 Answers2

1

With Javascript, you can select children properties with a string of the key in square brackets, so obj.key becomes obj['key']

Using this notation, you can rewrite the selectElement function to match below:

function selectElement(elementname){
      measurements.map(function(row){
          return row[elementname];
      });
};

We know that elementname is a string, which is used as a selector for the row object

Glen Keane
  • 62
  • 11
0

row.elementname looks for a key with the value "elementname". The dot notation does not do evaluation. Do

function selectElement(measurements, elementname){
      return measurements.map(function(row){
          return row[elementname];
      });
};

Aluminium = selectElement(measurements, 'Aluminium');
Iron = selectElement(measurements, 'Iron');
Kuba Wyrostek
  • 6,163
  • 1
  • 22
  • 40
pppetrov
  • 131
  • 5