Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 534
Kousha Avatar asked Sep 06 '25 03:09

Kousha


1 Answers

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);
like image 73
CertainPerformance Avatar answered Sep 07 '25 20:09

CertainPerformance