Convert API response to array

Viewed 88

I have a list of 1000 objects returned from an API; they are structured like

{
  val1: {col: 'hjkh', …}, 
  val2: {col: 'hekj', …},
  val3: {col: 'jhkd', …},
  val4: {col: 'kjdj', …},
  val5: {col: 'kjdj', …},
}

I would like to convert them using Javascript to something I can iterate as a map in React, something like this would be ideal;

const objects = [
  { name: 'val1', col: 'hjkh', …},
  { name: 'val2', col: 'hekj', …}
];
3 Answers

Use Object.entries

const data = {
  val1: {col: 'hjkh'}, 
  val2: {col: 'hekj'},
  val3: {col: 'jhkd'},
  val4: {col: 'kjdj'},
  val5: {col: 'kjdj'},
};
const result = Object.entries(data).map(([name, values]) => ({name, ...values}));

console.log(result);

You could do something like:

const data = {
  val1: {col: 'hjkh', …}, 
  val2: {col: 'hekj', …},
  val3: {col: 'jhkd', …},
  val4: {col: 'kjdj', …},
  val5: {col: 'kjdj', …},
};

const res = [];

Object.keys(data).forEach(key => {
  res.push({
     name: key, 
     ...data[key]
  });
});

I hope this gives a rough idea.

Use for...in to do just a single iteration.

let data = await api.get(); //your api call
let arr = [];
for (let prop in data) {
   arr.push({ name: prop, ...data[prop] });
}
Related