Skip to content
Advertisement

Reconstructing an array of arrays and turning it into an array of objects with keys as the first array and values as the rest of the array items

The question itself is probably in need of editing but hear me out pls. I have this:

[
    ["a","b","c"],
    ["apple", "orange", "banana"],
    ["kiwi", "tomato", "avocado"],
    ["beans", "asparagus", "spinach"]
]

I need it so that it will look like the one below:

[
    {"a":"apple", "b":"orange", "c":"banana"},
    {"a":"kiwi", "b":"tomato", "c":"avocado"},
    {"a":"a", "b":"asparagus", "c":"spinach"}
]

I have done something like this:

const rows = [
    ["a","b","c"],
    ["apple", "orange", "banana"],
    ["kiwi", "tomato", "avocado"],
    ["beans", "asparagus", "spinach"]
]

const dataObj = {};
const dataArr = [];

if (rows.length) {
        keys = rows[0];
        values = rows[0];

        rows.forEach((element, i) => {
          values = rows[i];
          keys.forEach((key, j) => {
            dataObj[key] = values[j];
            dataArr.push(dataObj);
          });
        });
      } 

To no avail and got something like this:

[
    {"a":"apple", "b":"orange", "c":"banana"},
    {"a":"apple", "b":"orange", "c":"banana"},
    {"a":"apple", "b":"orange", "c":"banana"}
]

This is not the desired output. If you can help me out – and our community! – it would be super. Thanks!

Advertisement

Answer

You can use couple of Array functions to achieve this:

  • Array.shift: To pick the first element and remove it from array
  • Array.map: To transform items into object

const rows = [
  ["a", "b", "c"],
  ["apple", "orange", "banana"],
  ["kiwi", "tomato", "avocado"],
  ["beans", "asparagus", "spinach"]
]

const keys = rows.shift();
const map = rows.map((item) => {
  const obj = {}
  keys.forEach((key, index) => {
    obj[key] = item[index]
  })
  return obj
})

console.log(map)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement