Richard Hamilton
Richard Hamilton

Reputation: 26434

Getting the length of an array inside an object

I have a JavaScript object which includes an array. I created a new key, length, which is supposed to store the value of the length of the fields array.

$(document).ready(function() {
var data = {
    "label": "Information",
    "fields": [
        {
            "name": "name",
            "label": "Team Name",
            "type": "string",
            "config": {}
        }
    ],
    "length": fields.length     // Need help with this line
};
$("button").click(function() {
    alert(data.length);
});
});

http://jsfiddle.net/kvtywmtm/

In my fiddle, nothing gets alerted, although it should alert 1, since there is 1 record in the fields array.

Any ideas?

Edit

I know you can get the length OUTSIDE of the object by creating a new variable

var length = data.fields.length;

However, I need the length to be inside of the object.

Upvotes: 1

Views: 2448

Answers (3)

AmmarCSE
AmmarCSE

Reputation: 30557

You can use a getter

$(document).ready(function() {
  var data = {
    "label": "Information",
    "fields": [{
      "name": "name",
      "label": "Team Name",
      "type": "string",
      "config": {}
    }],
    get 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>

Upvotes: 6

michelem
michelem

Reputation: 14590

Try this JSFiddle

I don't know what length you need in the alert, but if you need the object data properties length you need the following. Also, to pass fieldslength you need to add it after declare the array:

JS:

$(document).ready(function() {
    var data = {
        "label": "Information",
        "fields": [
            {
                "name": "name",
                "label": "Team Name",
                "type": "string",
                "config": {}
            }
        ]
    };

    data.length = data.fields.length

    $("button").click(function() {
        alert(Object.keys(data).length);
    });
});

Upvotes: 1

Jashaszun
Jashaszun

Reputation: 9270

var data = {
    "label": "Information",
    "fields": [
        {
            "name": "name",
            "label": "Team Name",
            "type": "string",
            "config": {}
        }
    ],
};
data.length = fields.length;

This won't auto-update the length field, but it doesn't seem as if you need it to.

Upvotes: 1

Related Questions