Reputation: 33
i have a json like this:
[
{
"part": "LM",
"section": "021",
"column": "001",
"description": "Descrizione attività/passività",
"type": "NUM"
},
{
"part": "LM",
"section": "021",
"column": "002",
"description": "Assenza cause Ostative Applicazione Regime",
"type": "CB"
},
{
"part": "LM",
"section": "042",
"column": "001",
"description": "Differenza su reddito",
"type": "NUM"
},
{
"part": "LM",
"section": "050",
"column": "006",
"description": "Perdite non compensate - Eccedenza 2018",
"type": "NUM"
}
]
and i wanna map items splitted for section prop. Aspect output is:
<div>section 021
<p>column 001</p>
<p>column 002</p>
</div>
<div>section 042
<p>column 001</p>
</div>
<div>section 050
<p>column 006</p>
</div>
How can dynamically pass the section prop as filter parameter?
I have tried something like: obj.filter((item) => item.section == "021").map((item) => ... and works but i want the "021" is dynamic for every value in the object.
Thank you very much guys
Upvotes: 0
Views: 442
Reputation: 23654
export default function App() {
const data = [
{
part: 'LM',
section: '021',
column: '001',
description: 'Descrizione attività/passività',
type: 'NUM'
},
{
part: 'LM',
section: '021',
column: '002',
description: 'Assenza cause Ostative Applicazione Regime',
type: 'CB'
},
{
part: 'LM',
section: '042',
column: '001',
description: 'Differenza su reddito',
type: 'NUM'
},
{
part: 'LM',
section: '050',
column: '006',
description: 'Perdite non compensate - Eccedenza 2018',
type: 'NUM'
}
];
const output = Object.values(
data.reduce((b, a) => {
if (b.hasOwnProperty(a.section)) b[a.section].columns.push(a.column);
else {
a.columns = [a.column];
b[a.section] = a;
}
return b;
}, {})
);
// console.log(output);
return (
<div>
{output.map(obj => (
<div>
{obj.section}
<ul>
{obj.columns.map(col => (
<li> {col} </li>
))}
</ul>
</div>
))}
</div>
);
}
View here: https://stackblitz.com/edit/react-txmy72?file=src/App.js
Upvotes: 1