Blankman
Blankman

Reputation: 267190

Creating an array of JSON values using my users collection retrieved from an API

In my React app, I load data from my API that returns a collection of users.

How could I then create an array with different properties, using the users collection as a source to generate this new json array like below?

export const userList = [
  { username: 'ocean', color: 'Ocean',},
  { username: 'blue', color: 'Blue',},
]

Each user in the users array that I load from my API has properties "user_name" and "fav_color".

users.map(user => {
  //user.user_name
  //user.fav_color
});

Upvotes: 0

Views: 175

Answers (2)

Artem Mirchenko
Artem Mirchenko

Reputation: 2170

You should just create your own fields.

Example:

const newUsers = userList.map(({username, color}) => ({
 user_name: username,
 fav_color: color
}));

Upvotes: 0

Chris Hawkes
Chris Hawkes

Reputation: 12420

users.map(user => {
  userList.push({ username: user.user_name, color: user.fav_color });
});

You map over the collection, create your custom data object and push those objects into the array of objects you will then pass along to your UI library to render.

Upvotes: 1

Related Questions