I’m trying to .map()
an object of arrays to create a div
for each key/value pair. Here is a sample of the object format:
const data = {
year: ["2018", "2020"],
make: ["Honda"],
model: ["Accord", "Civic"],
subModel: []
}
Here is what I have:
const filterChips = Object.entries(data)
.flatMap(([key, value]) => [value].flat()
.filter(v => v !== "" && v !== null)
.map(v => [key, v]))
.map(it => (<div>{it}</div>));
Which gives me the output:
<div>year2018</div>
<div>year2020</div>
<div>makeHonda</div>
<div>modelAccord</div>
<div>modelCivic</div>
Which is almost what I want, but I would like to be able to separate the key/value in each div
so last line of code is:
.map(it => (<div>{it.key}: {it.value}</div>));
So that the output would be:
<div>year: 2018</div>
<div>year: 2020</div>
<div>make: Honda</div>
<div>model: Accord</div>
<div>model: Civic</div>
I feel like I’m close, but tuck on the last part…
2
Answers
reducers give you a lot more flexibility.
You can use an inner
.map()
your innervals
arrays to divs, and then return this from your.flatMap()
to merge all the mapped divs into one array. No need to create a wrapperdiv
and call.flat
on that:To incorporate a filter, you can filter out before you
.map()
:Runnable Example: