Kousha
Kousha

Reputation: 36189

Object.defineProperties nested

Taking the example from mozilla, here is a simple case of Object.defineProperties

const object1 = {};

Object.defineProperties(object1, {
  property1: {
    value: 42,
    writable: true
  },
  property2: {}
});

What if I wanted to do a nested one, i.e. something like

const object1 = {};

Object.defineProperties(object1, {
  nested: {
    property1: {
      value: 42,
      writable: true
    },
    property2: {}
  }
});

This obviously does not work, but hopefully, it portrays what I want.

Upvotes: 4

Views: 2580

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370629

defineProperties can only be passed an existent object that you want to add properties to, and it will only define properties directly on that object. There's no way around defining the parent object ahead of time, in order to call defineProperties on a nested property:

const object1 = {nested: {}};

Object.defineProperties(object1.nested, {
  property1: {
    value: 42,
    writable: true,
    enumerable: true
  },
  property2: {
    enumerable: true
  }
});
console.log(object1);

Upvotes: 4

Related Questions