user3142695
user3142695

Reputation: 17332

javascript: add nested attribute in object

Wit this example object:

obj = {
    id: '123',
    attr: 'something'
}

Now I want to add the attribute link in the attribute data. Sometimes data is already existing, but in this example data doesn't exist.

So if I do

obj.data.link = 'www.website.com';

I get the error TypeError: Cannot set property 'link' of undefined.

Result should be:

obj = {
    id: '123',
    attr: 'something',
    data: {
        link: 'www.website.com'
    }
}

Upvotes: 0

Views: 55

Answers (3)

Gabriel Cuenca
Gabriel Cuenca

Reputation: 121

Javascript From 1.8.5 you can use the following method:

Object.defineProperty(obj, "data", {
    value: {'link' : 'www.website.com'},
    writable: true,
    enumerable: true,
    configurable: true
});

Good luck :)

Upvotes: 0

AtheistP3ace
AtheistP3ace

Reputation: 9691

You need to initialize the data property. You can do something like this:

var obj = {
    id: '123',
    attr: 'something'
};

obj.data = {};
obj.data.link = 'www.website.com';

In the case for the property existing you can check before assigning link.

if (!obj.data) {
    obj.data = {};
}

And as stated in another answer you can use the or operator which I've heard is 'curiously powerful' =]

obj.data = obj.data || {};

That basically means if this value ( obj.data ) exists use it and if it doesn't use the right operand ( {} ). This works because of short circuit evaluation.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074385

You need to create the data object first:

obj.data = {};
obj.data.link = 'www.website.com';

or you can do it all at once:

obj.data = {
    link: 'www.website.com'
};

if data may or may not already by there, there's a handy shortcut that will use the existing one if it's there or create a new one if not:

obj.data = obj.data || {};
obj.data.link = 'www.website.com';

That uses the JavaScript's curiously-powerful || operator.

Upvotes: 5

Related Questions