0

obj = [{
    prop11: 'value1',
    prop21: 'value2'
  },
  {
    prop12: 'value1',
    prop22: 'value2'
  },
  {
    key3: {}
  }
];

obj.forEach(element => {
  Object.defineProperty(obj.key3, 'prop1', {
    value: "xx",
    writable: true,
    enumerable: true,
    configurable: true
  })
});
console.log(obj.prop1)

getting error - Uncaught TypeError: undefined is not a non-null object tried several ways of this and also Object.defineProperties() but couldn't get working.

6
  • 1
    Only one of the elements in your array has a "key3" property, so the attempt will fail on the other elements.
    – Pointy
    Commented Jun 12 at 18:31
  • 1
    Also your .forEach() callback is incorrect anyway, because you reference obj instead of element.
    – Pointy
    Commented Jun 12 at 18:33
  • There's absolutely no reason to use Object.defineProperty here, and the error has nothing to do with it either. Same as obj.key3.prop1 = "xx". To fix it, use (element.key3 ??= {}).prop1 = "xx";
    – Bergi
    Commented Jun 12 at 19:24
  • sorry, if I use this expression error is gone but, outcome is undefined with above console statement. Also would like to know why should we not use defineProperty() as I'm trying to modify property value here. Commented Jun 13 at 7:47
  • console.log(obj.key3.prop1) gives me TypeError: obj.key3 is undefined Commented Jun 13 at 8:22

1 Answer 1

0

You need to correctly access key3 in your obj array and then define the property on it, To do so you need to find the object within the array that contains the key3 property after that create/define the property you need in the key3 object.

Refer the code below for reference:

let obj = [{
    prop11: 'value1',
    prop21: 'value2'
  },
  {
    prop12: 'value1',
    prop22: 'value2'
  },
  {
    key3: {}
  }
];


const key3Object = obj.find(element => element.key3); // get the object containing key3

if (key3Object && key3Object.key3) {
  Object.defineProperty(key3Object.key3, 'newProperty', {
    value: "newPropertyValueHere",
    writable: true,
    enumerable: true,
    configurable: true
  });
}

console.log(JSON.stringify(key3Object.key3.newProperty));  

1
  • Thanks, this piece of code is working fine but somehow, when I applied to my program, it is showing same error. Commented Jun 14 at 11:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.