2

Within the example script I have generated two arrays I would like to combine to a single row:

var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];

and

var testValue =  ["aValue","bValue", "cValue","dValue","eValue"];

What I am trying to achieve is a string like { aLabel = aValue, bLabel = bValue, ... } that can be used to upload into BigQuery (the data upload job works).

I found a piece of code that almost does this, but somehow it changes the order of the elements within the two arrays.

var code = testValue.reduce(function(obj, value, index) {

  obj[testHeaders[index]] = value;
  return obj

}, {})

However, the result does mix up the order of the arrays as seen below. I am not capable of figuring out why the order changes. As far as I know, reduce() should work its way from left to right in an array.

The returned object is:

{ 
  aLabel = aValue,
  dLabel = dValue,
  bLabel = bValue,
  eLabel = eValue,
  cLabel = cValue
}
Ivan
  • 34,531
  • 8
  • 55
  • 100
  • 4
    Objects do not have a set order. – VLAZ May 17 '18 at 11:44
  • 1
    *"What I am trying to achieve is a string like {aLabel=aValue, bLabel=bValue,.."* : **where** are you building a string ? The code you show only builds an object. Please build a [MCVE](https://stackoverflow.com/help/mcve) leading to the generation of the desired result. – Denys Séguret May 17 '18 at 11:45
  • Just a side note: the order of none of those arrays was changed. – Gerardo Furtado May 17 '18 at 11:50
  • I apologize for that - and thank you for the answers. The goal was in fact not to build a text string, but to build a function that converted a 2d array of strings into a format that BigQuery would accept. As mentioned by all of you, I should not consider the ordering of the returned object here. Thanks again, I appreciate that. – Steffen Davidsen May 17 '18 at 12:47

2 Answers2

2

You can use map and join:

var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
var testValue =  ["aValue","bValue", "cValue","dValue","eValue"];

var res = '{' + testHeaders.map((label, i) => `${label}=${testValue[i]}`).join(',') + '}';

console.log(res);
Faly
  • 13,291
  • 2
  • 19
  • 37
-1

As vlaz pointed out, you are creating neither a string or a new array, but an object. And just like maps, objects do not have a set order of keys in JavaScript. hence, there is quite a chance of getting another order in the object than in both arrays.

Lorenz Merdian
  • 722
  • 3
  • 14