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.
.forEach()
callback is incorrect anyway, because you referenceobj
instead ofelement
.Object.defineProperty
here, and the error has nothing to do with it either. Same asobj.key3.prop1 = "xx"
. To fix it, use(element.key3 ??= {}).prop1 = "xx";