Skip to content Skip to sidebar Skip to footer

Javascript Appending To 2-d Array

I am trying to append an array to an array. I am expecting the output to be something like: [[Dep,POR],[14073,99.25],[14072,0.06]] But I am getting: Dep,POR,14073,99.25,14072,0.06

Solution 1:

When you initialize hist_por, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:

hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]

Also per @justrusty's answer, you need to JSON.stringify(hist_por) when you pass it to document.write(). This is the more important piece so his answer should be accepted.

So the whole code block would become:

functionget_historical() {
  var well = document.getElementById('wellSelect'); 
  var selected_well = well.options[well.selectedIndex].value; 
  var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
  hist_por = [['Dep','POR']];
  for (var item in hist_json_obj) {
    if (hist_json_obj.hasOwnProperty(item)) {
       var dep = hist_json_obj[item].dep;
       var por = hist_json_obj[item].por;

       var arr_rop = [dep, parseFloat(por)];
       hist_por.push(arr_por);

    }
  }
  document.write(JSON.stringify(hist_por));
}

Solution 2:

This may help you https://codepen.io/anon/pen/xQLzXx

var arr = ['foo','bar'];
var arr2 = ['baz', 'boo']
arr.push(arr2);
console.log(arr);
document.write(arr);
document.write("<br>");
document.write(JSON.stringify(arr));

It's basically just the way it writes it to document. If you log it in console you'll see the array appended. Or if you JSON.stringify() first it will show as you expect.

My advice is ALWAYSconsole.log() so you can see exactly how the data is structured

Solution 3:

The others have already pointed out what the problem is (+ there's a typo in one of your variable names - arr_rop vs arr_por). Here's an ES6 version that will break in older browsers, for learning purposes:

functionget_historical() {
  const well = document.getElementById('wellSelect');
  const selected_well = well.options[well.selectedIndex].value;
  const hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));

  const hist_por = Object.values(hist_json_obj).reduce(
    (arr, item) => [...arr, [item.dep, +item.por]],
    [["Dep", "POR"]]
  );

  document.write(JSON.stringify(hist_por));
}

Post a Comment for "Javascript Appending To 2-d Array"