0

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!

2
  • Could you please show us some output that you want please ? Commented Jul 10, 2020 at 10:17
  • @ThanyathonPornsawatchai my nested object should be rendered e.g. as a list inside one table cell. So instead of having it as one string. i'd like to have it as a list. This is how it looks atm: screencast.com/t/LK0lfvgOT Commented Jul 10, 2020 at 10:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

got it to work by wrapping the d[key] = ... part in a <ul dangerouslySetInnerHTML .../> :-) thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.