1

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', …}
];
0

3 Answers 3

3

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);

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

Comments

0

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.

Comments

-1

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] });
}

3 Comments

What do you mean by "a single iteration"?
Here's the polyfill for Object.keys. You can see that it is looping. And then using Array.forEach or Array.map or a different solution with multiple loops is doing more than 1 iteration. That's what i mean, @CharlesBamford
The polyfill does not necessarily represent the engine implementation of a method. It's just a backwards compatibility layer, and given that this feature has existed in the spec since 2012, it would probably be better to just use the built in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.