如何获取JS Object中的最后一个属性值

时间:2017-10-19 10:22:17

标签: javascript arrays object

这里每次用户选择一些选项时,都会添加节点对象和状态,我需要发布最后一个节点对象的状态

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="content">
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
  </div>
  <div data-spy="affix" data-offset-top="150">
    <h1 class="bg-grey">This is sticky content</h1>
  </div>
  <div class="content">
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
    <p>Some content goes-here</p>
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

使用递归尝试此解决方案。

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));