0

I have this data:

const data = [
  {
    _id: '1',
    status: 'active',
    user: {
      email: '[email protected]',
      provider: 'google',
      profile: {
        image: 'https://example.com/image1.jpg',
      },
    },
  },
    {
      _id: '2',
      status: 'inactive',
      user: {
        email: '[email protected]',
        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

Here is what I have tried:

data.map((item) => (
  <tr key={item._id}>
    {body.map((i, index) => (
      <td key={index}>{item[i]}</td>
    ))}
  </tr>
))
4
  • is it react lib Commented Jun 29, 2022 at 11:10
  • this is supported in lodash with get in case you are using it. but something like this? stackoverflow.com/questions/6491463/… Commented Jun 29, 2022 at 11:11
  • @MohitSharma I forget to mention it. Yes it react Commented Jun 29, 2022 at 11:13
  • a bad way of achieving this using eval. eval(item.${i}) Commented Jun 29, 2022 at 11:23

2 Answers 2

1

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

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

Comments

1

If your body data is not dynamic you can do :

data.map((item) => (
  <tr key={item._id}>
      <>
      <td key={index}>{item._id}</td>
      <td key={index}>{item.status}</td>
      <td key={index}>{item.user.email}</td>
      <td key={index}>{item.user.profile.image}</td>
      <>
  </tr>
))

else you can use

const deeper = (data, array) => {
  if(array.length > 1){
    return deeper(data[array[0]], array.slice(1, array.length))
  } else {
    return data[array[0]]
  }
}

with

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

Something like that

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.