I
I
iharaleynikov2021-07-02 21:02:30
JavaScript
iharaleynikov, 2021-07-02 21:02:30

How to recursively traverse a tree object?

Let's say we have a tree structure object:

const obj = {
  something: {
    something1: 'value',
    something2: 'value1',
    something3: {
      something4: 'value2'
    }
  }
};

I want to recursively go through it and get, for example, only the keys of the object. How to do it? Help me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fedor Vlasenko, 2021-07-02
@iharaleynikov

const obj = {
  something: {
    something1: 'value',
    something2: 'value1',
    something3: {
      something4: 'value2'
    }
  }
}
const getKeys = obj => {
  const res = []
  for (const key in obj) {
    res.push(key)
    obj[key] && Object.getPrototypeOf(obj[key]) === Object.prototype && res.push(...getKeys(obj[key]))
  }
  return res
}
console.log(getKeys(obj))
//[ 'something', 'something1', 'something2', 'something3', 'something4' ]

Option

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question