2

I have an array:

   const arr = [
  {
    name: "name 1",
    dontShow: true,
    children: [
      {
        name: "name 2",
        key4: 4,
        dontShow: false,
        children: [],
      },
    ],
  },
  {
    name: "name 3",
    dontShow: false,
    children: [
      {
        name: "name 4",
        dontShow: true,
        children: [
          {
            name: "name 5",
            dontShow: false,
            children: null,
          },
        ],
      },
    ],
  },
];

I need an array of names from every object, except those that have property dontShow: true So from that example I would expect such array:

["name2", "name3", "name5"]

Basically, I need to get a flat array from tree-like structure, lodash/underscore solutions would be also great, I just didn't find them

0

2 Answers 2

1

You can use a recursive function

const arr = [{ name: "name 1", dontShow: true, children: [{  name:"name 2", key4: 4, dontShow: false, children: [], }, ],},{name: "name 3",dontShow: false,children: [{ name: "name 4", dontShow: true, children: [{ name: "name 5", dontShow: false, children: null,},],}, ],},];

let final = (arr, result = []) => {
  if (Array.isArray(arr)) {
    arr.forEach(obj => {
      if (!obj.dontShow) {
        result.push(obj.name)
      }
      if (Array.isArray(obj.children)) {
        final(obj.children, result)
      }
    })
  }
  return result
}

console.log(final(arr))

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

Comments

0

You could get a flat array of names with a look to dontShow.

const
    getNames = array => array.flatMap(({ name, dontShow, children }) => [
        ...(dontShow ? [] : [name]),
        ...getNames(children || [])
    ]),
    array = [{ name: "name 1", dontShow: true, children: [{ name: "name 2", key4: 4, dontShow: false, children: [] }] }, { name: "name 3", dontShow: false, children: [{ name: "name 4", dontShow: true, children: [{ name: "name 5", dontShow: false, children: null, }] }] }],
    result = getNames(array);

console.log(result);

Comments

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.