Home > Software engineering >  Set first element of nested array as object keys
Set first element of nested array as object keys

Time:11-12

I have an array like this:

var values = Array ( );

values [0] = Array ("", "Guest1", "Guest2", "Guest3")
values [1] = Array ("Name", "Hans", "Carl", "Peter")
values [2] = Array ("City", "Berlin", "Tokio", "Washington")
values [3] = Array ("Phone", "123", "234", "345")

I would like to create an object like this:

var data= {
   Guest1: { "Name" : "Hans", "City" : "Berlin", "Phone" : "123" },
   Guest2: { "Name" : "Carl", "City" : "Tokio", "Phone" : "234" },
   Guest3: { "Name" : "Peter", "City" : "Washington", "Phone" : "345" },
};

I got the first key using:

const data = Object.fromEntries(values[0].map(key => [key, 0]));
    delete data[""];

However, I am struggling to create the rest of the object.

CodePudding user response:

I would highly recommend finding a way to query your data in a more meaningful shape, but it can be wrangled.

const values = [
  ["", "Guest1", "Guest2", "Guest3"],
  ["Name", "Hans", "Carl", "Peter"],
  ["City", "Berlin", "Tokio", "Washington"],
  ["Phone", "123", "234", "345"],
]

const [header, ...rows] = values;

const data = {};
for (const [key, ...row] of rows) {
  for (const [i, value] of row.entries()) {
    (data[header[i   1]] ??= {})[key] = value;
  }
}

console.log(data);

Reference:

  • Related