Skip to content
Advertisement

moving the key of an object into its value to create an array of objects

I have an object I want to build a table out of however I need to use the value of the key as a part of the data displayed. My data looks like this:

{
    templates: {
      some_visit_1: {
        template: "A long block or rich text",
        editedAt: "timestamp",
        editedBy: "name",
      },
      some_visit_2: {
        template: "A different block of rich text",
        editedAt: "timestamp",
        editedBy: "Name",
      },
    },
  },

Ive tried using

let data = result.templates;
const templates = Object.entries(data);

But this gives me nested arrays inside with the key as one value and an object as the second. I would like to create an array of objects where each object contains the key and all values inside the initial object.

Taking this a step further I thought I could map over the new array and spread the data into an object but this just causes errors.

const templates = Object.entries(data).map((item, idx) => {
        const values = item[1];
        return {
          ...items,
          items: {
            name: item[0],
            editedAt: item[1].editedAt,
            editedBy: item[1].editedBy,
            template: item[1].template,
          },
        };
      });

Is there a method to combine the key and all values in an object into a single object?

like this:

[
   {
       {
        name: some_visit_1,
        template: "A long block or rich text",
        editedAt: "timestamp",
        editedBy: "name",
      },
      {
        name: some_visit_2,
        template: "A different block of rich text",
        editedAt: "timestamp",
        editedBy: "Name",
      }
]

Advertisement

Answer

Is this what is expected?. I used Object.entries and map

let data = {
  templates: {
    some_visit_1: {
      template: "A long block or rich text",
      editedAt: "timestamp",
      editedBy: "name",
    },
    some_visit_2: {
      template: "A different block of rich text",
      editedAt: "timestamp",
      editedBy: "Name",
    },
  },
}
let result = Object.entries(data.templates).map(([key, value]) => {
  return {
    name: key,
    ...value,

  }
});

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