wasddd_
wasddd_

Reputation: 1018

"Flatten" Nested Object for Data Table

Issue

I want to implement a data table on my project and the data I provide for the table looks like this:

data=[
  {
    key: "value",
    anotherKey: "bar",
  },
  {
    key: "value",
    anotherKey: {
      "nestedKey": "nestedValue",
      "foo": "bar"
    },
  },
  {
    key: "value",
    anotherKey: "foo",
  },
]

So basically I have an array of objects and some of the objects inside might contain nested data which also has to be rendered to the table.

Now, since I'm only "allowed" to pass an array of key/value paired objects to the table, this will break.

What i try to achieve

I want the nested objects to be in a renderable way so they can get rendered by the data table.

What I tried

const transformedData = data.map(d => {
  return Object.keys(d).forEach(key => {
    if (typeof key === "object") {
      d[key] = <p>{d[key]}</p>
    } 
  })
})

Unfortunately this didn't work out at all.

I am pretty sure that I am extremely overcomplicating things here and I'd appreciate any help. I have looked on google before but didn't find any reasonable answer.

Thanks!

Upvotes: 0

Views: 521

Answers (1)

Prakhar
Prakhar

Reputation: 1485

You were going in the right direction, by extending your solution I was able to come up with this

transformedData = data.map( v => {
    let d = {...v}
    Object.keys(d).forEach(key => {
        if (typeof d[key] === "object") {
            d[key] = Object.keys(d[key]).reduce((acc, nestedKey) => {
                return acc + '<p>' + nestedKey + ':' + d[key][nestedKey] + '</p>'
            }, '')
        }
    });
    return d;
})

It is working, but I am sure there can be a better solution than this.

Upvotes: 1

Related Questions