1

I have a list of filters to be applied to a data set using a simple key:value loop. When the user selects a filter, a new object is created with those key:value pairs. However, if there are 4 filters, and the user has selected only the 1st and 3rd filter items, the new object that is created is structured like this:

var newObject = {
  0: {
    key: value,
  },
  2: {
    key: value,
  }
}

When I call newObject.length, it returns 3. See the following from Chrome devtools:

devtools object description

Object.length seems to be based off of the last key in the object, rather than the number of objects themselves. How can I get the newObject.length to return 2 instead of 3?

Here is my function that creates the object based on the filters:

selectedInModel: function() {
  var selected = [];
  var getInputs = inputService.primaryInputs; // returns filter object
  for (var key in getInputs) {
    if (getInputs[key]["value"]) {
      selected[key] = {
        "value": getInputs[key]["value"],
        "id": getInputs[key]["id"]
      };
    }
  }
  return selected;
};

How can I get Object.length to return the number of objects in my object?

Himmel
  • 3,425
  • 3
  • 29
  • 65

1 Answers1

1

You are using [] as an object. length should give you the highest index regardless of how many properties. I would switch to using an object instead:

var selected = {};
selected[key] = {
    "value": getInputs[key]["value"],
    "id": getInputs[key]["id"]
};
Object.keys(selected).length;
beautifulcoder
  • 9,006
  • 3
  • 16
  • 26