Home > Software engineering >  How to map objects into ui?
How to map objects into ui?

Time:11-03

Currently I have some data in the format of

data : {
  full_name: 'John Doe',
  date_of_birth: '01-01-1990'
}

I want to render it in a table format which would sort of look like

Full Name : John Doe
Date Of Birth: 01-01-1990

If it was an array i could just to something like

data.map((item) => <h1>item</h1>

but i also need the to print the key .

How do i achieve something like this in a single loop like function? Could have used map in case of array but i also need to render the key part of the object.

NOTE: Data object cant be changed.

CodePudding user response:

You can map the entries array, like this:

Object.entries(data).map((entry, index) => (
    <div key={index}>{entry[0]}: {entry[1]}</div>
));

the Object.entries function creates an array of [key, value] arrays from the entries of the function.

Also, you may use a function that will convert keys from snake_case to readable format. Here is a one-line function that does this conversion:

   const snakeToText = (str) => str.split('_').map((word) => word[0].toUpperCase()   word.substring(1)).join(' ');

CodePudding user response:

Let say you have an object

const obj = {
  data: {
    full_name: "John Doe",
    date_of_birth: "01-01-1990"
  }
};

then you can use either of the following ways:

Live Demo

Codesandbox Demo

1) Using Object.keys

<div>
  {Object.keys(obj.data).map((key) => {
    return (
      <div> {key} - {obj.data[key]} </div>
    );
  })}
</div>

2) Using Object.entries

<div>
  {Object.entries(obj.data).map(([key, value]) => {
    return (
      <div>
        {key} - {value}
      </div>
    );
  })}
</div>

EDITED: If you want to convert my_name to My Name then you can create a utility function. You can use split, map, and join.

function convertString(str) {
  return str
    .split("_")
    .map((str) => str[0].toUpperCase()   str.slice(1))
    .join(" ");
}

and call this function as:

<div>
  {key.includes("_") ? convertString(key) : key} - {obj.data[key]}
</div>

CodePudding user response:

You need to convert your data in Object.entries or Object.values.

Object.entries() and Object.values()

Example :

Object.entries()

   const object1 = {
     a: 'somestring',
     b: 42
   };
        
    for (const [key, value] of Object.entries(object1)) {
       console.log(`${key}: ${value}`);
    }
    
    // expected output:
    // "a: somestring"
    // "b: 42"

Object.values()

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]

const data = {
  full_name: 'John Doe',
  date_of_birth: '01-01-1990'
};

const values = Object.entries(data);

console.log(values)

values.map(entry => console.log(entry[0]   " "   entry[1]));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

const data = {
  full_name: "John Doe",
  date_of_birth: "01-01-1990"
};
export default function App() {
  const renderableData = () =>
    Object.keys(data).map((k) => {
      const label = k
        .replaceAll("_", " ")
        .split(" ")
        .map((i) => i[0].toUpperCase()   i.slice(1))
        .join(" ");

      return (
        <div>
          <div style={{ display: "inline-block" }}>{label}: &nbsp;</div>
          <div style={{ display: "inline-block" }}>{data[k]}</div>
        </div>
      );
    });

  return <div>{renderableData()}</div>;
}

example here: https://codesandbox.io/s/crazy-hill-hfvl5?file=/src/App.tsx:0-560

CodePudding user response:

You can do this like ,

let data = {
  full_name: 'John Doe',
  date_of_birth: '01-01-1990'
}
Object.keys(data).map((eachKey)=>{
return `${eachKey} : ${data[eachKey]}`
})
  • Related