0

I have an empty object and want to create an object inside object dynamically.

const obj = {}
obj["test1"]["test1.1"] = x //initialize to some variable

I get the error

Uncaught TypeError: Cannot set property 'test1.1' of undefined

I want the output to be like

obj = {
   test1: {
       test1.1: x //some variable
   }
}
2
  • 1
    Why not just obj['test1'] = { 'test1.1': x } Commented Nov 20, 2020 at 6:53
  • Or why not literally const obj = { test1: { "test1.1": x } }? Then you make the declaration, assignment, and full object creation all at once. Commented Nov 20, 2020 at 6:56

5 Answers 5

6

By dynamically if you mean the name of the attribute is not certain, you can use brackets to insert dynamic variable names:

const arg1 = 'test1';
const arg2 = 'test1.1';
const x = 42;

// assign both variable names dynamically
const obj = { [arg1]: { [arg2]: x } };
console.log(obj);

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

1 Comment

Well guessed that this is what OP wanted.
2

You can do this in two steps or one

const x = "some var";
const obj = {};

obj["test1"] = {
  "test1.1": x
}; // assign the nested object 
console.log(obj);

// or 

const y = "some var";

const obj1 = {  // assign the complete object 
  test1: {
    "test1.1": x
  }
}; 
console.log(obj1);

Comments

1

You need to initialize obj["test1"] = {}

const obj = {}
obj["test1"] = {}
obj["test1"]["test1.1"] = 'x'

console.log(obj)


For the other solution using lodash library, you can use set() method.

var obj = {}
_.set(obj, ["test1", "test1.1"], 'x');
console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

4 Comments

I did that too but is there any way I can do that in one line
You can use lodash setWith() method - lodash.com/docs/4.17.15#setWith
can you add the lodash part to your answer so that I can mark that as the answer? I think it would help people if they are looking for the one line solution
i thought OP wants the dynamic key for the future use, and the question just was an example. didn't notice that he definitely wanted that obj with one simple nested obj @mplungjan
0

A more functional approach

const arr = {};

// respecting immutability
const rewroteArray = {...arr, da: {"foo": 2}}

console.log(rewroteArray);

Comments

0

As creating an Object with this syntax const obj = {} is equal const obj = new Object(). You can use the second method to define any level deep of properties definition.

const obj = new Object({
  "test1": {
    "test-1":'x'
  }
});

console.log(obj);

1 Comment

No need for new Object() at all

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.