Categories
React-js

React Map Array Of Objects

Most of the time we feel need to iterate over objects and display them in jsx form or in HTML page. In react we can simply use the pure JavaScript function of “map()” to iterate over the arrays or even the arrays of objects and we can simply output the corresponding data. Here is one of the simplest example of displaying array of objects in React.

Let’s assume we have an object like following

const mocCred = [
  { id: 1, username: "some", email: faker.internet.email() },
  { id: 1, username: "Test2", email: faker.internet.email() },
  { id: 1, username: "Test3", email: faker.internet.email() },
  { id: 1, username: "asodin", email: faker.internet.email() },
];Code language: JavaScript (javascript)

Here in above code you may noticed that I used the faker object to create the emails. This is simple faker.dev which is faker js library to create fake object data.

Moving back, we can simply iterate over objects and display them in React like this

import React from "react";
import PanelLayout from "../../layouts/panel";
import { faker, Faker } from "@faker-js/faker";

const mocCred = [
  { id: 1, username: "some", email: faker.internet.email() },
  { id: 1, username: "Test2", email: faker.internet.email() },
  { id: 1, username: "Test3", email: faker.internet.email() },
  { id: 1, username: "asodin", email: faker.internet.email() },
];

function AddCred() {
  return (
    <PanelLayout>
      <div>
        {mocCred.map((val, index) => {
          return (
            <>
              <p key={index}>{val.email}</p>
              <hr />
            </>
          );
        })}
      </div>
    </PanelLayout>
  );
}

export default AddCred;
Code language: PHP (php)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.