0

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);
2
  • 2
    Please show an simple example of the structure of your object, so that we can help you better. Commented Feb 22, 2014 at 2:41
  • This question is incomplete without showing us an example of the data you are searching through and a boilerplate/description of a function you want written (e.g. what info you're going to pass it and what info you want it to return). Commented Feb 22, 2014 at 3:15

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Yes. That is precisely what I mean. It is the same thing but its in the rows object in an ng-grid. Each cell can have an array based on the field name and I need to count the number of arrays in the field children.
@user3250966 - Please use the "edit" button in your question to paste in an example of the actual data you're searching.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.