user348173
user348173

Reputation: 9288

create child objects if they don't exist

For example I have object:

person = {
            Name: 'John',
            Address: {
               Name: 'NY'
            }
         }

and I have array of properties:

0: Name,
1: Address.Name,
2: Car.Name

I want to create all properties(object) if they don't exist. For example above, I want to get:

 {
       Name: 'John',
       Address: {
          Name: 'NY'
       },
       Car: {
          Name: null
      }
 }

PS. The array is dynamically builded. I don't know which properties there are.

Upvotes: 1

Views: 393

Answers (4)

techfoobar
techfoobar

Reputation: 66663

To add missing properties, you can iterate through the properties, check if it is present in the object and add as required.

// original object
var person = {
    Name: 'John',
    Address: {
        Name: 'NY'
    }
};

// list of all properties
var props = ['Name', 'Address.Name', 'Car.Name'];

// iterate through the properties and add as needed
props.forEach(function(prop) {
    var root = person;
    prop = prop.split('.'); // split by . to use [] notation subsequently
    for(var i=0; i<prop.length; i++) {
        if(typeof root[prop[i]] === 'undefined') root[prop[i]] = (i === prop.length-1 ? null : {});
        root = root[prop[i]];
    }
});

console.log(person);
/*
{
    Name: 'John',
    Address: {
        Name: 'NY'
    },
    Car: {
        Name: null
    }
}
*/

Upvotes: 3

ManirajSS
ManirajSS

Reputation: 2375

If particular property is not yet created typeof will return undefined . you can make use of that to create new property.

if(typeof Car.Name === "undefined")
Car.Name = null; //initialize to some value

Upvotes: 0

Vova Bilyachat
Vova Bilyachat

Reputation: 19494

I dont understand why you need that but as i understand its useless.

If you need that to validate if value is set you can do simply

var result = (person.Address && person.Address.Name) //true will be returned if address and address name are not null and defined.

Upvotes: 0

Thoronwen
Thoronwen

Reputation: 608

You could first create an object with all the properties set to null, and then use $.extend to merge them together.

obj = {
       Name: null,
       Addess: {
          Name: null
       },
       Car: {
          Name: null
      }
 };
person = {
       Name: 'John',
       Addess: {
          Name: 'NY'
       }
};
person = $.extend(true,obj,person);

Upvotes: 0

Related Questions