Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert dot notation string array into an object JavaScript and render to table?

I have this data:

const data = [
  {
    _id: '1',
    status: 'active',
    user: {
      email: 'one@mail.com',
      provider: 'google',
      profile: {
        image: 'https://example.com/image1.jpg',
      },
    },
  },
    {
      _id: '2',
      status: 'inactive',
      user: {
        email: 'two@mail.com',
        provider: 'github',
        profile: {
          image: 'https://example.com/image2.jpg',
        },
      },
    },
]


const head = ['_id', 'status', 'email', 'image']

const body = ['_id', 'status', 'user.email', 'user.profile.image']

I want to display in the table dynamically only show the string in the body array.

I tried and it worked _id, and status but not the string which contains dot

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is what I have tried:

data.map((item) => (
  <tr key={item._id}>
    {body.map((i, index) => (
      <td key={index}>{item[i]}</td>
    ))}
  </tr>
))

>Solution :

here is my way to achieve your desire output.
use this function

function getDeepObjValue (item, s) {
   return s.split('.').reduce((p, c) => {
      p = p[c];
      return p;
   }, item);
};   

use it like this

data.map((item) => {
    return (
       <tr key={item._id}>
          {body.map((keys, i) => {
             return <td key={i}>{getDeepObjValue(item, keys)}</td>;
          })}
       </tr>
    );
})  

and if you want to check demo click here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading