How to dynamically add property of nested object JavaScript
Adding a property to a nested JavaScript object is quite simple if we do it using the recursive approach. Our use case was, we have a nested object and we needed to add an attribute to each object of that nested object.
Following is our nested object:
const obj = { "key": "0", "props": { "children": [ { "key": "1", "props": { "children": [ "This is bold text" ] }, }, { "key": "2", "props": { "href": "google.com", "children": [ "Google anchor" ] }, } ] }, };
From the above object, we had to add an attribute where the object has a props attribute. Following is the code that does it:
const setDynamicAttr = (obj) => { if (typeof obj === 'object') { obj['constructor'] = undefined; } if(obj.hasOwnProperty("props")){ obj.props.children.map(item => { return setDynamicAttr(item); }); } return obj; }; const result = setDynamicAttr(obj); console.log(result);