Home > Back-end >  How to display all object key with map function in react
How to display all object key with map function in react

Time:01-27

I want to display all keys when nested array object keys also I tried alot with map function but cannot able to display nested array object

  const item = 
  
[
  {
    "A": "asd",
    "B": "asde1",
    "C": [
      {"A": "Asd", "B": "Asd1", "C": "asd22",  }, ]}]

return (
 { item.map((item) => (
       <View>
      <Text>{Object.keys(item)}</Text>
         
       </View>
   )
)
}
)

CodePudding user response:

  1. Your function is returning an object. Remove the braces surrounding your .map() call.
  2. Object.keys() returns an array, which can't be rendered directly. You can either join this array's members into a string, or map it to multiple text elements.

CodePudding user response:

You can run below code snippet to check if it is what you want

const data = [{
  "A": "asd",
  "B": "asde1",
  "C": [{
    "A": "Asd",
    "B": "Asd1",
    "C": "asd22"
  }]
}]

let keysArray = [];

findKeys = (arrayOfObj) => {
  arrayOfObj.map(item => {
    const itemKeys = Object.keys(item);
    keysArray = [...keysArray, ...itemKeys]
    itemKeys.map(keyItem => {
      if (Array.isArray(item[keyItem])) {
        findKeys(item[keyItem])
      }
    })
  })
}

findKeys(data)

console.log(keysArray)

If yes then call findKeys function in useEffect or wherever you wish to call and then, map keysArray to get what you want like this

return(
 <View>
   {keysArray.map(item=>(
     <Text>item</Text>
   )}
 </View>
)
  •  Tags:  
  • Related