Home > Blockchain >  Render data from array of object based on a particular property as a heading in React
Render data from array of object based on a particular property as a heading in React

Time:07-11

I have an array of object like below -

{
   name:"Thor",
   universe:"Marvel",
   type:"God"
},
{
   name:"Batman",
   universe:"DC",
   type:"Human"
},
{
   name:"Iron man",
   universe:"Marvel",
   type:"Human"
},
];

Now, let's suppose that I want to render the objects such that the details of type Human are together, and the details of type God are together.

Basically, I want to display data based on the type property like below -

**Human**
name: Batman   universe:DC
name: Iron man universe:Marvel

**God**
name: Thor universe: Marvel

I hope the problem statement is clear. Many thanks in advance.

CodePudding user response:

I can help you with classification. You can do render your self.

const data=[{
   name:"Thor",
   universe:"Marvel",
   type:"God"
},
{
   name:"Batman",
   universe:"DC",
   type:"Human"
},
{
   name:"Iron man",
   universe:"Marvel",
   type:"Human"
},
];
const category={};
for(let i of data){
category[i.type]??=[]
category[i.type].push(i)
}

Category like:

{
   "God":[
      {
         "name":"Thor",
         "universe":"Marvel",
         "type":"God"
      }
   ],
   "Human":[
      {
         "name":"Batman",
         "universe":"DC",
         "type":"Human"
      },
      {
         "name":"Iron man",
         "universe":"Marvel",
         "type":"Human"
      }
   ]
}

CodePudding user response:

I would first format the data type to an easy to use data type: See example below:

function App() {
  const characters = [
    {
      name: "Thor",
      universe: "Marvel",
      type: "God",
    },
    {
      name: "Batman",
      universe: "DC",
      type: "Human",
    },
    {
      name: "Iron man",
      universe: "Marvel",
      type: "Human",
    },
  ];

  const charactersObj = {};
  characters.forEach((character) => {
    const { type } = character;
    if (charactersObj[type]) {
      const currentArray = [...charactersObj[type]];
      currentArray.push(character);
      charactersObj[type] = currentArray;
    } else {
      charactersObj[type] = [character];
    }
  });

  return (
    <div>
      {Object.entries(charactersObj).map(([charType, charData]) => {
        return (
          <div>
            <p> {charType}</p>
            {charData.map(({name, universe}) =>  <p>name: {name} universe: {universe} </p>)}
        
          </div>
        );
      })}
    </div>
  );
}

CodePudding user response:

Try this, do map on finalArray variable and render name, universe etc.

const data = [
    {
   name:"Thor",
   universe:"Marvel",
   type:"God"
},
{
   name:"Batman",
   universe:"DC",
   type:"Human"
},
{
   name:"Iron man",
   universe:"Marvel",
   type:"Human"
},
];

const _human = data.filter(item => item.type === "Human");
const _god = data.filter(item => item.type === "God");
const finalArray = [..._human, ..._god];

console.log('>>>human', _human);
console.log('>>>god', _god);
console.log('>>>merge', finalArray);

CodePudding user response:

Without changing your data structure, you can just map over the type

const App = () => {
    return (
        <div>
            Human:
            <div>
                {heroes.map((hero) =>
                    hero.type === "Human" ? <div>{hero.name}</div> : null,
                )}
            </div>
            God:
            <div>
                {heroes.map((hero) =>
                    hero.type === "God" ? <div>{hero.name}</div> : null,
                )}
            </div>
        </div>
    );
};

CodePudding user response:

you can try something like this

const data = [{
   name:"Thor",
   universe:"Marvel",
   type:"God"
},
{
   name:"Batman",
   universe:"DC",
   type:"Human"
},
{
   name:"Iron man",
   universe:"Marvel",
   type:"Human"
},
];

const transform = data => data.reduce((res, {type, ...rest}) => {

  return {
   ...res,
   [type]: [...(res[type] || []), rest]
  }

},{})

const toTemplate = (type, data) => {
return `**${type}**
${data.map(({name, universe}) => `name: ${name}   universe: ${universe}`).join('\n')}`
}
const toHtml = (data) => Object.entries(transform(data)).map(d => toTemplate(...d)).join('\n\n')

console.log(toHtml(data))

  • Related