0

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.

2
  • how are you getting this data? There has to be a way to receive it in a more meaningful shape. Commented Nov 11, 2022 at 23:40
  • I get it from a google sheet, the code for this is const response = await fetch( sheets.googleapis.com/v4/spreadsheets/${ID}/values/${RANGE}?key=${API_KEY}` ); const { values } = await response.json();` Commented Nov 11, 2022 at 23:42

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.