1

I am using the html2json which gives me back an object with child objects. Like the code below. I want to get the value of the key text. But it differs per case how many child objects there are and thus where the key text is situated.

The code I have tried but for this reason, did not work every time was this one:

json.child[0].child[0].child[0].child[0].text

And this is an example of an object:

  node: 'root',   child: [
    {
      node: 'element',
      tag: 'div',
      attr: { id: '1', class: 'foo' },
      child: [
        {
          node: 'element',
          tag: 'h2',
          child: [
            { node: 'text', text: 'sample text with ' },
            { node: 'element', tag: 'code', child: [{ node: 'text', text: 'inline tag' }] }
          ]
        }
      ]
    }   ]

Is there another way to access this element? I was thinking of searching for a key in the object because the key "text" only occurs once. But do not know how this would work.

All help is really appreciated!

Emilie van Eps
  • 121
  • 1
  • 9
  • Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Sebastian Simon Oct 27 '20 at 16:56

1 Answers1

0

You could create a recursive function that will return an array of all the values where the key matches.

const data = {"node":"root","child":[{"node":"element","tag":"div","attr":{"id":"1","class":"foo"},"child":[{"node":"element","tag":"h2","child":[{"node":"text","text":"sample text with "},{"node":"element","tag":"code","child":[{"node":"text","text":"inline tag"}]}]}]}]}

function findByKey(data, key) {
  const result = [];

  for (let i in data) {
    if (i === key) result.push(data[i]);
    if (typeof data[i] === 'object') {
      result.push(...findByKey(data[i], key))
    }
  }

  return result;
}

console.log(findByKey(data, 'text'))
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176