I have an object and I want one of the values to be the name of the parent key:
{
name: 'Jon',
address: {
city: 'Vienna',
parent: <How can I dynamically set this to 'address'>
}
}
I have an object and I want one of the values to be the name of the parent key:
{
name: 'Jon',
address: {
city: 'Vienna',
parent: <How can I dynamically set this to 'address'>
}
}
well i cant understand from your question if you handle nested objects with more then 1 level but this code will work for the first level. if you want unlimited levels you need to do it with recursion
const obj = {
name: 'Jon',
address: {
city: 'Vienna'
}
}
for(let i in obj){
if(typeof obj[i] === 'object'){
obj[i].parent = i;
}
}
console.log(obj)
We can achieve this by making a recursive function which recursively updates all the levels inside the object and child objects with the parent property. Here is a recursive function which will work for n-levels.
var obj = {
name: 'Jon',
address: {
city: 'Vienna',
pincode :{
val : 110,
Area : {
val : "xyz"
}
},
},
designation : {
post : "Manager",
salary : {
value : "100"
}
}
}
function updateParent(obj,parent){
if(parent)
obj.parent = parent;
for(var key in obj){
if(obj[key].constructor.toString().indexOf("Object") >= 0){
updateParent(obj[key],key);
}
}
}
updateParent(obj);
console.log(obj);
The approach I took was to make the object iterable then use a for...of
to search for the desired child property and change the value to it's parent object's name:
var data = {
name: 'Jon',
address: {
city: 'Vienna',
parent: '<How can I dynamically set this to \'address\'>'
}
};
data[Symbol.iterator] = function() {
var i = 0;
var keys = Object.keys(this);
return {
next: function() {
var value = keys[i],
done = false;
i++;
if (i > keys.length) {
done = true;
}
return {
value,
done
}
}
}
}
function setChildProperty(parentPropertyName, childPropertyName) {
for (prop of data) {
if (prop == parentPropertyName) {
data[prop][childPropertyName] = prop;
}
}
}
//Before
console.log(data);
setChildProperty("address", "parent")
//After
console.log(data);