0

I don't know if I am mind-collapsed or just need to work harder with objects, but I don't get why this doesn't work:

const obj = {};
const obj['pagination']['searchword'] = searchWord;

It says:

Cannot set property 'searchWord' of undefined

It looks like I can't create that kink of object:

console.log(obj)
{
pagination:{searchWord:valueOfSearchWordVariable}
}

I tried to with const obj.pagination['searchword'] = searchWord;

2
  • 4
    obj['pagination'] is undefined you need to initialise it Commented Apr 26, 2020 at 9:25
  • 2
    const obj = { pagination: { searchword: searchWord } }; Commented Apr 26, 2020 at 9:26

2 Answers 2

1

If you want to create an object inside an object, you have to define the object explicitly somewhere. If you try to access a property of an object as if it was a nested object, one won't automatically be created.

For your case, it would be easier to define the object all at once, in one statement, not two:

const obj = {
  pagination: {
    searchword: searchWord
  }
};

If you have to assign after object initialization, then you'd do:

obj.pagination = {
  searchword: searchWord
};

If you change the searchWord variable name so it matches the lower-case property name, you can use shorthand notation:

obj.pagination = {
  searchword
};
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, I thought js was faster than that. The code snipet is more complex that what I wrote above, after this object comes promise and overwrite it, taken the last object and not adding this one that it is the first. Thanks, very well explained! Lot of problems with promises and objects in my life. I really need to understand them or I am dead. Thanks everybody
It's not really an issue of writing concise code (or not being able to), it's an issue of code doing exactly what you tell it to do - if you want to define an object as a property, you need to tell the interpreter to do so explicitly. If I don't define a property beforehand, I wouldn't want the interpreter to automatically create an object for me.
1

You have to define obj['pagination'] first. Now you are assigning to an undefined.

obj is an empty object. But what is obj['pagination']? it is not set yet. And while obj['pagination'] is not set you are trying to assign a property to it.

you also can assign an empty object.

obj['pagination'] = {};

and then you can do this.

obj['pagination']['searchword'] = searchWord;

Another way to do this

Object.defineProperty(obj, 'pagination', { searchword: searchWord });

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.