-1

I have two JavaScript obj like so:

const objOne = {
  "firstname": "xzxz",
  "lastname": "xzxzxzx"
};

const objTwo  = {
  "title": [
    {
      "name": "foo",
      "table": "First"
    },
    {
      "name": "bar",
      "table": "Second"
    }
  ]
};

and I want to combine them like below (not sure if "combine" is the appropriate word but hopefully make sense)

{
  "firstname": "xzxz",
  "lastname": "xzxzxzx",
  "title": [
    {
      "name": "foo",
      "table": "First"
    },
    {
      "name": "bar",
      "table": "Second"
    }
  ]
}

so far I tried the below

   let result = [];
     results.push(objOne);
     results.push(objTwo);

but surely the result is not the one I want and it make sense as I create an array and I push into both objects.

[
  {
    "firstname": "xzxz",
    "lastname": "xzxzxzx"
  },
  {
    "title": [
      {
        "name": "foo",
        "table": "First"
      },
      {
        "name": "bar",
        "table": "Second"
      }
    ]
  }
]
user2342259
  • 345
  • 2
  • 9
  • 27
  • Just a nitpick, but you don't have JSON. You have objects. JSON is a _string representation_ of data that _resembles_ object syntax. – gen_Eric Nov 18 '20 at 19:24
  • 1
    @ Rocket Hazmat I agree, two obj which I wanted to be serialized like so, my brain was fried when i was writing this question...Spent few hours on this, it seems that this question was even answered already. I should have used "merge" when I was googling this but being a java boy...for me a merge is merge. – user2342259 Nov 18 '20 at 19:47

2 Answers2

5

const objOne = {
  "firstname": "xzxz",
  "lastname": "xzxzxzx"
};

const objTwo  = {
  "title": [
    {
      "name": "foo",
      "table": "First"
    },
    {
      "name": "bar",
      "table": "Second"
    }
  ]
};

const output = { ...objOne, ...objTwo };
console.log(output);
wangdev87
  • 8,611
  • 3
  • 8
  • 31
2

You could use Object.entries() to convert the objects into arrays and Object.fromEntries to convert it back into an object.

const objOne = {
  "firstname": "xzxz",
  "lastname": "xzxzxzx"
};

const objTwo  = {
  "title": [
    {
      "name": "foo",
      "table": "First"
    },
    {
      "name": "bar",
      "table": "Second"
    }
  ]
};

const combined = Object.fromEntries(
  Object.entries(objOne)
  .concat(Object.entries(objTwo))
);

console.log(combined);
Yousername
  • 1,012
  • 5
  • 15