Search code examples
javascriptobjectjavascript-objects

Is there anyway to add many objects inside an object variable that is constructed just with object?


I want to add more than one object inside a variable contructed just with object. Language (Javascript). Example: var x = {"a": {}, "b": {"name": "Hello World"}};

I'm trying to add more than one object for the x.a, but when i add more than one in x.a and when i request some value of these objcts that i've added to x.a, the console back undefined. i would like to know if i can add more than one objects without using array.

var x = {"a": {}, "b": {"name": "Hello World"}};
x.a = {"name": "Paradox"};
x.a += {"first", "Hello"};
x.a += Object.assign({"second", "World"});
console.log(x.a.first);// Returns undefined

When put console.log(x.a.first) it returns undefined. I know that using array i would get the results i want that is "Hello". But i would like to know if i can add many objects and get the same results without using array.


Solution

  • Your current logic wont work because += is used for concatenation, you can't concatenate objects, or even arrays like that.

    There's many options you can use to do what you want, I'll show you two of them:

    First: Using x.a as an object (that you already have), you can create a key on the run and assing a value to it, then accessing x.a["keyName"] will return the value, for example: x.a["first"] will return "Hello".

    var x = {
      "a": {},
      "b": {
        "name": "Hello World"
      }
    };
    
    x.a["name"] = "Paradox";
    x.a["first"] = "Hello";
    
    console.log(x.a)
    console.log(x.a.first);

    Second: Using x.a as an array of objects. You create an object with key/value and insert into this array, but, to find a value, you'll need to iterate over the array, there's many ways to do that, here I'm using find(), check the code for better understanding.

    var x = {
      "a": [],
      "b": {
        "name": "Hello World"
      }
    };
    
    x.a.push({"name": "Paradox"});
    x.a.push({"first": "Hello"});
    
    console.log(x.a.find(y => y["first"]))