Skip to content

Transform an array with attributes into a list

I am working with a graphics library and it is very bad to manipulate the data coming from the API. The problem is that the chart lib does not accept the data format that the api I am using returns.

API response

const data = [
  {
      "house01": {
        "free": 6
      },
      "house02": {
        "free": 2
      },
      "house03": {
        "free": 1
      },
  }
]

Expected (UPDATED)

const data = [
          {
            "label": "house01"
            "free": 6
          },
          {
            "label": "house02"
            "free": 2
          },
          {
            "label": "house03"
            "free": 1
          },
    ]

Answer

Is this what you’re looking for?

const data = [
  {
    house01: {
      free: 6
    },
    house02: {
      free: 2
    },
    house03: {
      free: 1
    }
  }
];

const expectedData = Object.entries(data[0]).map(d => ({
  label: d[0],
  free: d[1].free
}));

console.log(expectedData)

const data2 = {
  house01: { free: 6 },
  house02: { free: 2 },
  house03: { free: 1 }
};

const expectedData2 = Object.entries(data2).map(d => ({
  label: d[0],
  free: d[1].free
}));

console.log(expectedData2);