Ad

Generate Children Element Based On Number Of Keys In Object

- 1 answer

I have my object that is stored in variable val.Main.widgets. I also have variable that functions as a data tree. What I need is to generate as many children elements as there are keys in my object that is stored in val.Main.widgets. If I console log this: console.log(Object.keys(val.Main.widgets).length;, it returns 8 so in this case I need to generate 8 children elements.

I am guessing I need some sort of cycle, but I really dont know where to start, hence why I am asking here.

Here is my object:

enter image description here

And here is my tree variable:

const tileTree = [
  {
    name: val.Main.name,
    children: [
      {
        name: val.Main.widgets['E1EV7'].name,
      },
      {
        name: val.Main.widgets['E70ZT'].name,
      },
    ],
  },
];

Thank you for any advice.

Ad

Answer

You do not need lodash for this. You want to use Array.map on the result of Object.keys.

const content = val.Main.widgets;
const keys = Object.keys(content);
const children = keys.map(key => content[key]);

Then in your tileTree you simply set children to children.

const tileTree = [
  {
    name: val.Main.name,
    children,
  },
];

This will give you all the properties of the val.Main.widgets object. If you only want specific ones, you can destructure them in your map function.

...
// Suppose we only want 'name'.
const children = keys.map(key => {
  const { name } = content[key];
  return { name };
});
...
Ad
source: stackoverflow.com
Ad