ja-br
ja-br

Reputation: 11

Converting JS arrays into objects from table

First my solution

    function convertTable(table){
  let newArray = []
  for(let i=0; i<table.length-1; i++){
    newArray.push({})
  }
  for(let j=0; j<newArray.length; j++){
     for (const key of table[0]) {
      newArray[j][key] = table[j+1][table[0].indexOf(key)];
      console.log(key)
 }
  }
  return newArray
}

What I'm doing is taking an array that holds other arrays which each represents a table row such as

const tableData = [
  ["header_one", "header_two", "header_three", "header_four"],
  ["blah", "blah", "blah", "blah"],
  ["blah", "blah", "blah", "blah"],
  ["blah", "blah", "blah", "blah"]
]

And making it output

    [
  { header_one : "blah", header_two : "blah", header_three: "blah", header_four : "blah" },
  { header_one : "blah", header_two : "blah", header_three: "blah", header_four : "blah" },
  { header_one : "blah", header_two : "blah", header_three: "blah", header_four : "blah" }
]

I feel like there must be some better ways to do this

Upvotes: 1

Views: 45

Answers (2)

user12407908
user12407908

Reputation:

You can use .map() to create the objects, and .reduce() on each one to create each object.

const tableData = [
  ["header_one", "header_two", "header_three", "header_four"],
  ["blah", "blah", "blah", "blah"],
  ["blah", "blah", "blah", "blah"],
  ["blah", "blah", "blah", "blah"]
];

const headers = tableData[0];

const result = tableData.slice(1).map(a =>
  a.reduce((o, v, i) => ({...o, [headers[i]]: v}), {})
);

console.log(result);

It first separates out the headers, and then uses .map() on a slice of the remaining arrays.

In .reduce() it uses spread syntax to return a new object with the accumulation so far plus the current header (key) and value.


Or here's the same solution, but it swaps the .reduce() array to be the headers, with the lookup for the value on the current mapped array.

const tableData = [
  ["header_one", "header_two", "header_three", "header_four"],
  ["blah", "blah", "blah", "blah"],
  ["blah", "blah", "blah", "blah"],
  ["blah", "blah", "blah", "blah"]
];

const headers = tableData[0];

const result = tableData.slice(1).map(a =>
  headers.reduce((o, h, i) => ({...o, [h]: a[i]}), {})
);

console.log(result);

Upvotes: 1

Ele
Ele

Reputation: 33726

You can use the function Array.prototype.reduce to build the desired output.

const tableData = [  ["header_one", "header_two", "header_three", "header_four"],  ["blah", "blah", "blah", "blah"],  ["blah", "blah", "blah", "blah"],  ["blah", "blah", "blah", "blah"]],
      {result} = tableData.reduce((r, arr, i) => {
        if (i) r.result = r.result.concat(r.properties.reduce((a, p, pi) => Object.assign(a, {[p]: arr[pi]}), {}));
        else r.properties = arr;

        return r;
      }, {result: [], properties: []});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions