Im working on a ReactJS project and in my data structure, i have 2 buttons: ATM, and PARKING:
buttons: [
{
value: 'ATM',
icon: 'atm',
floors: [
{
value: 'L1',
floor: 0,
},
{
value: 'L2',
floor: 0,
},
]
},
{
value: 'PARKING',
icon: 'parking',
floors: [
{
value: 'L1',
floor: 0,
},
{
value: 'L2',
floor: 0,
},
]
},
],
I want to target the available floors values: 'L1'
, 'L2'
of ATM and display it as individual titles on HTML.
My approach is first to apply a filter for ATM, then map out the floors like so:
const filteredButton = _.filter(buttons, {value : 'ATM'}); // Filter for ATM
const mappedAtm = filteredButton.map((item)=>(item.floors)) // Map for Floors
const mappedFloor = mappedAtm.map((floors)=>(floors.value)) // Map for Floors values
However, when I console.log(mappedFloor)
it returns undefined
My expected output is: "L1", "L2"
Ideally if i get mappedFloor to work, i would then display it on html like so(on browser it should show 2 span tags):
<p className="floors">
{
mappedFloor.map((items, i) => (
<span key={i}>
{items}
</span>
))
}
</p>
Any suggestions and tips are greatly appreciated.
CodePudding user response:
Your filter returns an array, the first map makes it an array of array and the second expects it to be an array of objects.
To fix that, you can either use a Array.prototype.find
instead of the filter:
buttons.find((e) => e.value === 'ATM').floors.map((e) => e.value)
Or treat your last map as an array of array of objects and not as an array of objects.
CodePudding user response:
You can also do that by making one common function that will run on button onClick
event that will return that what you want is assume and in function passing an argument of array and property which you want to filter
// function that filter with respect to value property and return floors array, i assume that what you want
const filterFloors = (floorsArray,filteredProperty) => {
return floorsArray.find((item) => {if (item.value === filteredProperty) return item.floors
}).floors
}
console.log(filterFloors(buttons,'ATM'));
console.log(filterFloors(buttons,'PARKING'))