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

Iterate array objects in js

I have an array objects
it looks like

\[
{id: 1, name: 'first', properties: \[{id: 1, name: 'propName1'}, {id: 2, name: 'propName2'}\]},
{id: 2, name: 'second', properties: \[{id: 1, name: 'propName1'}, {id: 2, name: 'propName2'}\]},
{id: 3, name: 'third', properties: \[{id: 1, name: 'propName1'}, {id: 2, name: 'propName2'}\]},
\]

I want to display firtly name of object for example ‘first’ and then I want to display names of properties objects propName1, propName2
so I want to see

first

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

propName1
propName2

second

propName1
propName2

third

propName1
propName2

Could you help me, guys?

I tried
` {filters.map((filter) => {
let propss = ArrayFrom(filter.properties);
propss.map((prop) => (
<div>{prop.displayName}</div>
))
return(
<div className={style.title}>{filter.displayName}</div>

          )
          filter.properties.map((prop) => {
            return (
              <>
                <div className={style.title}>{filter.displayName}</div>
                <div>{prop.displayName}</div>
              </>
            );
          });
        })}`

and I tried to save array via reduce, but without any result

>Solution :

First of all, you should not name yout array ‘filter’ since this can be confused with the Array.prototype.filter method 😉

Then you have an array of objects containing arrays, so you should iterate at the two level (in case your real structure actually gots more depth, you probably need to take a recursive approach).

considering your entry point :

const data = [
  {
    id: 1,
    name: 'first',
    properties: [
      {id: 1, name: 'propName1'},
      {id: 2, name: 'propName2'}
    ]
  }, {
    id: 2,
    name: 'second',
    properties: [
      {id: 1, name: 'propName1'},
      {id: 2, name: 'propName2'}
    ]
  }, {
    id: 3,
    name: 'third',
    properties: [
      {id: 1, name: 'propName1'},
      {id: 2, name: 'propName2'}
    ]
  },
]

the two iterations couls look like somthing like that :

return data.map(entry => (
  <>
    <div className={style.title}>{entry.name}</div>
    {entry.properties.map(prop => (
      <div>{prop.name}</div>
    ))}
  <>
))
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