Home > database >  React JS / ANTD: Create new object entries from exisiting object array
React JS / ANTD: Create new object entries from exisiting object array

Time:10-12

I am currently working with ANTD and React v18.

I want to display my data inside the table. For this, I need to create objects with regarding index and values.

The logic for a table is like this:

const dataSource = [
  {
    key: '1',
    name: 'Mike',
    age: 32,
    address: '10 Downing Street',
  },
];

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
  },
  {
    title: 'Address',
    dataIndex: 'address',
    key: 'address',
  },
];

<Table dataSource={dataSource} columns={columns} />;

Now I have an object array like this:

const personData = [
    {
        "_id": "C84113",
        "Firstname": "Hola",
        "Lastname": "Tester",
        "__typename": "Person"
    },
    {
        "_id": "C_C84113_0",
        "Firstname": "Hermanoi",
        "Lastname": "Oko",
        "__typename": "Person"
    }
]

How can I map or push these values, that I receive something like this ?

//we create the respective columns


const personTableColumn = [
    { title: 'Person (Teilakte)', dataIndex: 'personName' },
    { title: 'ID', dataIndex: 'personID' },
  ];


//I want to have it like this
//personData.foreach() or push()
{
   "key":"i",
   "personName":"Person.Firstname  " "  Person.Lastname",
   "personID":"Person.ID>"
}

CodePudding user response:

You can iterate over the array and use the map function to create a new array with the object you need.

const personDataSource = personData.map((person, i) => {
  return {
    key: i,
    personName: person.Firstname   " "   person.Lastname,
    personID: person._id
  };
});

The personDataSource will have JSON object:

[
  { key: 0, personName: "Hola Tester", personID: "C84113" },
  { key: 1, personName: "Hermanoi Oko", personID: "C_C84113_0" }
]
  • Related