Reputation: 139
I have a generic function that needs to check the number of items in the array that is named, but I don't always know what the name is going to be called. Is there a way to do this?
array:
// added array example here per request:
var myArray = { "name": "myname", "data": [ "item1": [1], "item2": [2,3,4,5,6,7,8,9], "item3": [41,42,51,491]}
// where length is the number of objects in the array.
var mycount = someitem.getProperty("UnknownName").length;
what I want to do is call some function that does this:
var mycount = specialCountFunction(someitem, name);
Upvotes: 0
Views: 107
Reputation: 95
Do you mean to get the length of an array in an object?
For example, your object
var obj = {
"children": [ "john", "mark", "sam" ]
}
Get the length with obj["children"].length
Or the length of an object ?
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(obj);
Upvotes: 1
Reputation: 10972
In your specialCountFunction()
, receive the property name as a string, and then use square brackets after item
to evaluate the value of the string in order to use it as a property name.
function specialCountFunction(item, name) {
return item[name].length;
}
So then you'd call it like this:
var name = "whatever_the_name_is";
var count = specialCountFunction(someitem, name);
Upvotes: 1