1

Here each time users selects some option, the node object is added and the state, I need the state of a last node object to post

var breadCrumb = [{
      breadCrumbN: {
          node: {
            state: "test",
            node: {
              state: "test^test2",
              node: {
                state: "test^test2^test3",
                node: {
                 state: "test^test2^test3^test4" // like to post the last state. the node object will be added for each selection
                }
              }
            }
          }
        }
    }]
Sai c
  • 31
  • 1
  • 6

1 Answers1

2

Try this solution with recursion.

let obj =  {
   node: {
      state: "test",
      node: {
         state: "test^test2",
         node: {
            state: "test^test2^test3",
            node: {
               state: "test^test2^test3^test4"
            }
         }
      }
   }
};

function getLastNodeState(obj) {
   return obj.node ? getLastNodeState(obj.node) : obj.state;
}

console.log(getLastNodeState(obj));
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • I have the object inside a array, in that case? – Sai c Oct 19 '17 at 10:39
  • No matter, you need to call this function for every item's `breadCrumbN` property - getLastNodeState(item.breadCrumbN) – Suren Srapyan Oct 19 '17 at 10:40
  • Cool, got it. Thank you! here: var x = function chase() { var y = { name: "test" } return y } how to add that last value to y object? – Sai c Oct 19 '17 at 10:57
  • You can from my above code get not `state` property, but the object itself – Suren Srapyan Oct 19 '17 at 11:00
  • The above snippet works great. I appended the end value to a variable. Now that I just want to add that variable to a object which is in the above mentioned structure. var x = function chase() { var y = { name: "test" } return y } – Sai c Oct 19 '17 at 11:06
  • Look. From the above code just return the `obj`. In it access the `state` and get it value to make another one. After it when you already have the last object which is the `obj`, create on it a new property with the result value – Suren Srapyan Oct 19 '17 at 11:12
  • cool, thanks a lot! – Sai c Oct 19 '17 at 11:14