Search code examples
javascriptobjectarray-map

Javascript transform array of object structure


I am trying to transform an array of objects structure from looking like this:

[
  {
    id: 1,
    val: "bool",
    name: "somename",
    entities: [
      {
        id: 1,
        name: "varchar",
        type: "string"
      }
    ]
  },
  {
    id: 2,
    val: "bool",
    name: "somename",
    entities: [
      {
        id: 1,
        name: "varchar",
        type: "string"
      }
    ]
  }
]

Into this:

[
  {
    id: 1,
    val: "bool",
    name: "somename",
    entitiesName: "varchar",
    entitiesType: "string"
  },
  {
    id: 2,
    val: "bool",
    name: "somename",
    entitiesName: "varchar",
    entitiesType: "string"
  }
]

So more or less I want to take two values from entities and make them into key/values in the root object instead.

I have tried using Object.entries(data).map() but I am stuck


Solution

  • You could use a destruction for collecting all wanted properties and build a new object.

    var array = [{ id: 1, val: "bool", name: "somename", entities: [{ id: 1, name: "varchar", type: "string" }] }, { id: 2, val: "bool", name: "somename", entities: [{ id: 1, name: "varchar", type: "string" }] }],
        result = array.map(
            ({ id, val, name, entities: [{ name: entitiesName, type: entitiesType }] }) =>
            ({ id, val, name, entitiesName, entitiesType })
        );
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }