Home > other >  why map method won't return array items inside my span? -REACT
why map method won't return array items inside my span? -REACT

Time:06-14

lets say we have array of object like this

dynamicField : [
{a: ['One','Two'], b: '1'},
{a: ['One'], b: '1'},
{a: ['One','Two','Three'], b: '1'}
]

i want to show all strings inside property a in a span

my code

 {dynamicField.length > 0 &&
        dynamicField.forEach((item) =>
          item[a].map((arrayItem,index) => <span key={index}>{arrayItem}</span>)
        )}

before writing <span>{arrayItem}</span> i did a console.log(arrayItem) and map method returned every item in array but it won't show it in span. what is wrong with this code?

CodePudding user response:

forEach callback doesn't return the results, you need to use two maps:

 let data = [
    {a: ['One','Two'], b: '1'},
    {a: ['One'], b: '1'},
    {a: ['One','Two','Three'], b: '1'}
    ]
    
let result = data.map(x=>x.a.map(y=>y)) // use spans in last map

console.log(result)

  • Related