Search code examples
javascriptarraysobjectjavascript-objects

Convert array values to object keys


I do a get which returns me a json object like so:

"data": [
  [
    "2016 Pass/Fail Rates by Test Centre",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    ""
  ],
  [
    "",
    "Passes",
    "",
    "No ID",
    "",
    "Fails",
    "",
    "Fail Dangerous",
    "",
    "Total"
  ],
  [
    "Sometown",
    "8,725",
    "53.40%",
    "140",
    "0.90%",
    "7,417",
    "45.40%",
    "48",
    "0.30%",
    "16,330"
  ],
  [
    "Some Other Town",
    "12,778",
    "44.80%",
    "193",
    "0.70%",
    "15,422",
    "54.10%",
    "103",
    "0.40%",
    "28,496"
  ],
  [...many more identically formatted arrays...]

and I would like to end up with:

[{
    "Location": "Sometown",
    "Passes": 8,
    725,
    "Pass%": 53.40 % ,
    "No ID": 140,
    "NoID%": 0.90 % ,
    "Fails": 7,
    417,
    "Fail%": 45.40 % ,
    "Fail Dangerous": 48,
    "FailDangerous%": 0.30 % ,
    "Total": 16,
    330
  }, {
    "Location": "Some Other Town",
    "Passes": 8,
    725,
    etc etc...

So I want to ignore the first array inside the "data" array, use the values of the second array as keys (and replace the empty strings with something more useful) and the values in all remaining arrays as values in the resulting object.

So it is quite the multipart problem, though I suspect a fairly simple one. What is the simplest way to do that - and if different, what is the leanest way to do it in terms of processing/page load?

Thanks in advance,


Solution

  • You could take the second array as keys for the wanted objects and iterate only the part after the keys. Then iterate the keys and build a new object for the values of the array. Return the object for mapping for a new array.

    var data = { data: [["2016 Pass/Fail Rates by Test Centre", "", "", "", "", "", "", "", "", ""], ["Location", "Passes", "Passes%", "No ID", "No ID%", "Fails", "Fails%", "Fail Dangerous", "Fail Dangerous%", "Total"], ["Sometown", "8,725", "53.40%", "140", "0.90%", "7,417", "45.40%", "48", "0.30%", "16,330"], ["Some Other Town", "12,778", "44.80%", "193", "0.70%", "15,422", "54.10%", "103", "0.40%", "28,496"]] },
        keys = data.data[1],
        result = data.data.slice(2).map(function (a) {
            var temp = {};
            keys.forEach(function (k, i) {
                temp[k] = a[i];
            })
            return temp;
        });
        
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }