Ramil Shavaleev
Ramil Shavaleev

Reputation: 402

Can I count the number of properties of an object if this object is a property of parent object in the property of this parent object when creating

I'm trying to count the number of properties of the FORMAT_LST object in the FORMAT_LST_COUNT property when creating the UTILS object

var UTILS = {
    FORMAT_LST: {
        'FORMAT1': 'format1',
        'FORMAT2': 'format2',
        'FORMAT3': 'format3'
    },
    FORMAT_LST_COUNT: Object.keys(this.FORMAT_LST).length
}

but it causes the error "Uncaught TypeError: Cannot convert undefined or null to object"

Upvotes: 0

Views: 54

Answers (5)

Emil S. Jørgensen
Emil S. Jørgensen

Reputation: 6366

Going totally overboard with complexity, this can be achieved by using the defineProperties method and defining get FORMAT_LST_COUNT as the length of keys.

var UTILS = Object.defineProperties({}, {
  FORMAT_LST: {
    value: {
      'FORMAT1': 'format1',
      'FORMAT2': 'format2',
      'FORMAT3': 'format3'
    },
    enumerable: true
  },
  FORMAT_LST_COUNT: {
    get: function() {
      return Object.keys(this.FORMAT_LST).length;
    },
    enumerable: true
  }
});

console.log(UTILS);

Upvotes: 1

weegee
weegee

Reputation: 3409

Simply wrapping your code in the function block and returning it will do. Because else, the object does not know the statement and interprets it as another usual value.

var UTILS = {
  FORMAT_LST: {
    'FORMAT1': 'format1',
    'FORMAT2': 'format2',
    'FORMAT3': 'format3'
  },
  FORMAT_LST_COUNT: function() { // function block
    return Object.keys(this.FORMAT_LST).length // return it
  }
}

console.log(UTILS.FORMAT_LST_COUNT()) // execute it

Upvotes: 1

shrys
shrys

Reputation: 5960

If it can be a function

var UTILS = {
  FORMAT_LST: {
    'FORMAT1': 'format1',
    'FORMAT2': 'format2',
    'FORMAT3': 'format3'
  },
  FORMAT_LST_COUNT: function() {
    return Object.keys(this.FORMAT_LST).length
  }
}
console.log(UTILS);
console.log(UTILS.FORMAT_LST_COUNT());

If it needs to be a property:

var UTILS = new function() {
  this.FORMAT_LST = {
    'FORMAT1': 'format1',
    'FORMAT2': 'format2',
    'FORMAT3': 'format3'
  };
  this.FORMAT_LST_COUNT = Object.keys(this.FORMAT_LST).length
}
console.log(UTILS);

Upvotes: 1

jank
jank

Reputation: 870

Use Object.assign() in next line.

var UTILS = {
    FORMAT_LST: {
        'FORMAT1': 'format1',
        'FORMAT2': 'format2',
        'FORMAT3': 'format3'
    }
}
Object.assign(UTILS, {
  FORMAT_LST_COUNT: Object.keys(UTILS.FORMAT_LST).length
})
console.log(UTILS);

Upvotes: 0

YuraGon
YuraGon

Reputation: 147

Try something like that:

var UTILS = {
    FORMAT_LST: {
        'FORMAT1': 'format1',
        'FORMAT2': 'format2',
        'FORMAT3': 'format3'
    }
}

UTILS.FORMAT_LST_COUNT = Object.keys(UTILS.FORMAT_LST).length

Upvotes: 0

Related Questions