Home > Enterprise >  how too display nested key and value pairs in table
how too display nested key and value pairs in table

Time:12-19

data [
   {
      "09/12/2000": [
         "info1"   
      ]
   },
   {      
      "06/12/2000": [
         "info2",
         "info3"
      ]
   }
],

i want table like this how to dispaly using javascript(https://i.stack.imgur.com/bNGjo.png)

CodePudding user response:

const data = [{
    "09/12/2000": [
      "info1"
    ]
  },
  {
    "06/12/2000": [
      "info2",
      "info3"
    ]
  }
]

const App = () => {
  const PreviewData = () => {
    return data.reduce((acc, value) => {
      Object.entries(value).forEach(([date, value2]) => {
        value2.forEach((value3) => {
          acc.push([date, value3])
        })
      })

      return acc
    }, [])
  }

  return (
    <table>
      {PreviewData().map(([date,info])=>(
        <tr>
          <td>{date}</td>
          <td>{info}</td>
        </tr>
      ))}
    </table>
  )
}

ReactDOM.render(<App />, document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

CodePudding user response:

You can try this one and play around it:

let data = [
  { "09/12/2000": ["info1"] },
  { "06/12/2000": ["info2","info3"] }
];


for(let i=0; i < data.length; i  ){
  for(let key in data[i]) {
    for(let j=0; j<data[i][key].length; j  ){
      console.log(key   " : "   data[i][key][j]);
    }
  }
}

CodePudding user response:

here is the answer you can get the duplicated object with the same key when you have unique value

  const data = [{ "09/12/2000": ["info1"]},
                { "06/12/2000": ["info2","info3"]}
               ];
        
 const fun =(ar)=>{
  return ar.map((e, i)=>{
    for(x in e){
     if(Array.isArray(e[x])){
       return e[x].map((g)=>{return {[x] : g}})
     }
    }
  }).flatMap((eg)=> eg)
}
 
 console.log(fun(data))
next you can get the keys and values with for..in loop method

  • Related