0

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'
    }
}
1
  • or just obj.data = { link: 'www.website.com' } .... Commented Nov 7, 2015 at 17:41

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

curiously powerful - nice phrase - though, that page neglects the almost equally intriguing && and what you can do with a combination of && and ||
@JaromandaX: I thought it did mention it, but I just checked and you're right! May need to revise it a bit. :-)
1

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.

2 Comments

Missed that in question. Updated answer. Sorry! Thanks for heads up. =]
go curiously powerful ™
0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.