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); }); });
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
Post a Comment