javascript - Getting the length of an array inside an object -


i have javascript object includes array. created new key, length, supposed store value of length of fields array.

$(document).ready(function() { var data = {     "label": "information",     "fields": [         {             "name": "name",             "label": "team name",             "type": "string",             "config": {}         }     ],     "length": fields.length     // need line }; $("button").click(function() {     alert(data.length); }); }); 

http://jsfiddle.net/kvtywmtm/

in fiddle, nothing gets alerted, although should alert 1, since there 1 record in fields array.

any ideas?

edit

i know can length outside of object creating new variable

var length = data.fields.length; 

however, need length inside of object.

you can use getter

$(document).ready(function() {    var data = {      "label": "information",      "fields": [{        "name": "name",        "label": "team name",        "type": "string",        "config": {}      }],      length() {        return this.fields.length      }    };    $("button").click(function() {      console.log(data.length);    });  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>  <button>click here</button>


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -