Convert JavaScript array of arrays into object key value pairs

I have an input array

let data = [
    ["", "usa", "canada"],
    ["2015", "20", "40"],
    ["2016", "30", "60"],
    ["2017", "20", "50"],
    ["2018", "60", "80"],
]

I need the output in json format like this

"data": {
    "2015": {
        "usa": 20,
         "canada": 40
    },
    "2016": {
        "usa": 30,
         "canada": 60
    },

    "2017": {
        "usa": 20,
         "canada": 50
    },

    "2018": {
        "usa": 60,
         "canada": 80
    }
}

As you can see, the first element in the first array is an empty string. I don’t need it in the output json. How to accomplish this using map/filter or for loop?

What have you tried so far? For what it’s worth, I wouldn’t use map and filter on this.

1 Like

Welcome, codenoobie.

This is not very scale-able, but it is a quick-fix:

let jsonData = {};
for (let i = 1; i< data.length; i++) {
  let ob1 = data[i][1];
  let ob2 = data[i][2];
  jsonData[data[i][0]] = { 'usa':ob1, 'canada':ob2 };
}
1 Like

Hey. Thanks for the help. This works! But is there a way without hardcoding the object keys ‘usa’ and ‘canada’?

Sure. Use data[0][1] and data[0][2].

In this case, length of each individual inner arrays is 3. It can also be more than 3.

You could do that. Think about how.

I’m a bit off topic, but is there any particular reason why you wouldn’t use map here?

I wrote variations with reduce and map, with for loops, and with just map. The Big O should be equivalent (or I’ve miscalculated it), and the readability of both the map and for loop versions seemed comparable to me (the reduce version feels a bit brutal).

Are there specific style/perf/cognitive complexity improvements you had in mind when leading the OP away from map (and filter)?

Because the goal here is to convert an array to a single object. map and filter are for converting an array to another array.

1 Like