Search code examples
javascriptarraysobjectrecursionjavascript-objects

JavaScript Recursion identify last element


I have a piece of code here, and i wanted to identify the last element paragraph 3 and add some text like - last item and the output would be paragraph 3 - last item.

I would prefer if its recursive since there is no limit on the number children in an object.

obj = {
    content: [
        { text: "paragraph 1" },
        { 
            content: [
                { text: "paragraph 2" },
            ]
        },
        { text: "paragraph 3" },
    ]
}

Another example would be this, its output should be paragraph 5 - last item

obj = {
    content: [
        { text: "paragraph 1" },
        { 
            content: [
                { text: "paragraph 2" }
            ]
        },
        { text: "paragraph 3" },
        { 
            content: [
                { text: "paragraph 4" },
                { 
                    content: [
                        { text: "paragraph 5" }
                    ]
                }
            ]
        }
    ]
}

Solution

  • A simple implementation. Checks the key name and if it's content, it'll recall itself with the last element. Else, it'll return it.

    const obj1 = {
      content: [{
        text: "paragraph 1"
      }, {
        content: [{
          text: "paragraph 2"
        }]
      }, {
        text: "paragraph 3"
      }]
    };
    
    const obj2 = {
      content: [{
          text: "paragraph 1"
        },
        {
          content: [{
            text: "paragraph 2"
          }]
        }, {
          text: "paragraph 3"
        },
        {
          content: [{
              text: "paragraph 4"
            },
            {
              content: [{
                text: "paragraph 5"
              }]
            }
          ]
        }
      ]
    }
    
    function getLatestParagraph(obj) {
      for (const key in obj) {
        if (key === "content") return getLatestParagraph(obj[key].pop());
        return obj[key];
      }
    }
    
    console.log(getLatestParagraph(obj1))
    console.log(getLatestParagraph(obj2))