Max
Max

Reputation: 33

How to correctly merge two arrays of objects?

I have following array with objects in it:

[
  {
    name: "test",
    sub: {
      name: "asdf",
      sub: {}
    }
  },
  {
    name: "models",
    sub: {}
  }
]

And i have also folowing object:

{
  name: "test",
  sub: {
    name: "asdf",
    sub: {
      name: "inside_asdf",
      sub: {}
    }
  }
}

Now i want to somehow merge the two so that i get an array that looks like this:

[
  {
    name: "test",
    sub: {
      name: "asdf",
      sub: {
        name: "inside_asdf",
        sub: {}
      }
    }
  },
  {
    name: "models",
    sub: {}
  }
]

The problem is i don't know how to do that. Also i want that this works with any array depth so if i want to merge an array to the sub of "inside_asdf" it also works. Hope someone could help me. I also already tried Object.merge but this doesn't output the required result. I am thankful for every info or solution. Thanks in advance.

##FIX##
I marked the correct answer below. However because i programmed the whole application in react with typescript i found a nother solution to this problem.

Upvotes: 2

Views: 160

Answers (1)

Thomas J.
Thomas J.

Reputation: 643


Updated answer gives outcome what you desire, however it is, using jQuery, prototype $.extend.

Not that I wrapped once again, the aaaa with [] array tag, since it needs to have same structure.

Full code to acheve what you want:

var data = [
  {
    name: "test",
    sub: {
      name: "asdf",
      sub: {}
    }
  },
  {
    name: "models",
    sub: {}
  }
];

var aaaa = [{
    name: "test",
    sub: {
      name: "asdf",
      sub: {
        name: "inside_asdf",
        sub: {}
      }
    }
  }];


console.log($.extend({}, data, aaaa));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions